Laravel 5.4 добавить картинку
Мой код контроллера для загрузки файла в laravel 5.4:
if ($request->hasFile('input_img')) {
if($request->file('input_img')->isValid()) {
try {
$file = $request->file('input_img');
$name = rand(11111, 99999) . '.' . $file->getClientOriginalExtension();
$request->file('input_img')->move("fotoupload", $name);
} catch (Illuminate\Filesystem\FileNotFoundException $e) {
}
}
}
Изображение было успешно загружено, но код выдал исключение:
FileNotFoundException в строке MimeTypeGuesser.php 123
В файле есть какая-либо ошибка в моем коде или это ошибка в laravel 5.4, может ли кто-нибудь помочь мне решить проблему?
Мой код просмотра:
<form enctype="multipart/form-data" method="post" action="{{url('admin/post/insert')}}">
{{ csrf_field() }}
<div class="form-group">
<label for="imageInput">File input</label>
<input data-preview="#preview" name="input_img" type="file" id="imageInput">
<img class="col-sm-6" id="preview" src="">
<p class="help-block">Example block-level help text here.</p>
</div>
<div class="form-group">
<label for="">submit</label>
<input class="form-control" type="submit">
</div>
</form>
Ответы
Ответ 1
Попробуйте этот код. Это решит вашу проблему.
public function fileUpload(Request $request) {
$this->validate($request, [
'input_img' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if ($request->hasFile('input_img')) {
$image = $request->file('input_img');
$name = time().'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/images');
$image->move($destinationPath, $name);
$this->save();
return back()->with('success','Image Upload successfully');
}
}
Ответ 2
Вы можете использовать его простым способом, используя метод store
в вашем контроллере
как показано ниже
Сначала мы должны создать форму с вводом файла, чтобы мы могли загрузить наш файл.
{{Form::open(['route' => 'user.store', 'files' => true])}}
{{Form::label('user_photo', 'User Photo',['class' => 'control-label'])}}
{{Form::file('user_photo')}}
{{Form::submit('Save', ['class' => 'btn btn-success'])}}
{{Form::close()}}
Вот как мы можем обрабатывать файл в нашем контроллере.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
public function store(Request $request)
{
// get current time and append the upload file extension to it,
// then put that name to $photoName variable.
$photoName = time().'.'.$request->user_photo->getClientOriginalExtension();
/*
talk the select file and move it public directory and make avatars
folder if doesn't exsit then give it that unique name.
*/
$request->user_photo->move(public_path('avatars'), $photoName);
}
}
Вот оно. Теперь вы можете сохранить $photoName
в базу данных как значение поля user_photo
. Вы можете использовать функцию asset(‘avatars’)
в своем представлении и получить доступ к фотографиям.
Ответ 3
Используйте следующий код:
$imageName = time().'.'.$request->input_img->getClientOriginalExtension();
$request->input_img->move(public_path('fotoupload'), $imageName);
Ответ 4
Хорошей логикой для вашего приложения может быть что-то вроде:
public function uploadGalery(Request $request){
$this->validate($request, [
'file' => 'required|image|mimes:jpeg,png,jpg,bmp,gif,svg|max:2048',
]);
if ($request->hasFile('file')) {
$image = $request->file('file');
$name = time().'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/storage/galeryImages/');
$image->move($destinationPath, $name);
$this->save();
return back()->with('success','Image Upload successfully');
}
}
Ответ 5
public function store()
{
$this->validate(request(), [
'title' => 'required',
'slug' => 'required',
'file' => 'required|image|mimes:jpg,jpeg,png,gif'
]);
$fileName = null;
if (request()->hasFile('file')) {
$file = request()->file('file');
$fileName = md5($file->getClientOriginalName() . time()) . "." . $file->getClientOriginalExtension();
$file->move('./uploads/categories/', $fileName);
}
Category::create([
'title' => request()->get('title'),
'slug' => str_slug(request()->get('slug')),
'description' => request()->get('description'),
'category_img' => $fileName,
'category_status' => 'DEACTIVE'
]);
return redirect()->to('/admin/category');
}
Ответ 6
if ($request->hasFile('input_img')) {
if($request->file('input_img')->isValid()) {
try {
$file = $request->file('input_img');
$name = time() . '.' . $file->getClientOriginalExtension();
$request->file('input_img')->move("fotoupload", $name);
} catch (Illuminate\Filesystem\FileNotFoundException $e) {
}
}
}
или следуйте инструкциям
https://laracasts.com/discuss/channels/laravel/image-upload-file-does-not-working
или
https://laracasts.com/series/whats-new-in-laravel-5-3/episodes/12
Ответ 7
Я думаю, лучше сделать это
if ( $request->hasFile('file')){
if ($request->file('file')->isValid()){
$file = $request->file('file');
$name = $file->getClientOriginalName();
$file->move('images' , $name);
$inputs = $request->all();
$inputs['path'] = $name;
}
}
Post::create($inputs);
на самом деле изображения - это папка, в которой laravel делает ее автоматической, а файл - это имя ввода, и здесь мы сохраняем имя изображения в нашем столбце пути в таблице и сохраняем изображение в каталоге public/images
Ответ 8
// get image from upload-image page
public function postUplodeImage(Request $request)
{
$this->validate($request, [
// check validtion for image or file
'uplode_image_file' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048',
]);
// rename image name or file name
$getimageName = time().'.'.$request->uplode_image_file->getClientOriginalExtension();
$request->uplode_image_file->move(public_path('images'), $getimageName);
return back()
->with('success','images Has been You uploaded successfully.')
->with('image',$getimageName);
}
Ответ 9
Intervention Image - это библиотека PHP для обработки и обработки изображений с открытым исходным кодом http://image.intervention.io/
Эта библиотека предоставляет много полезных функций:
Основные примеры
// open an image file
$img = Image::make('public/foo.jpg');
// now you are able to resize the instance
$img->resize(320, 240);
// and insert a watermark for example
$img->insert('public/watermark.png');
// finally we save the image as a new file
$img->save('public/bar.jpg');
Метод цепочки:
$img = Image::make('public/foo.jpg')->resize(320, 240)->insert('public/watermark.png');
Советы: (в вашем случае) https://laracasts.com/discuss/channels/laravel/file-upload-isvalid-returns-false
Советы 1:
// Tell the validator input file should be an image & check this validation
$rules = array(
'image' => 'mimes:jpeg,jpg,png,gif,svg // allowed type
|required // is required field
|max:2048' // max 2MB
|min:1024 // min 1MB
);
// validator Rules
$validator = Validator::make($request->only('image'), $rules);
// Check validation (fail or pass)
if ($validator->fails())
{
//Error do your staff
} else
{
//Success do your staff
};
Советы 2:
$this->validate($request, [
'input_img' =>
'required
|image
|mimes:jpeg,png,jpg,gif,svg
|max:1024',
]);
Функция:
function imageUpload(Request $request) {
if ($request->hasFile('input_img')) { //check the file present or not
$image = $request->file('input_img'); //get the file
$name = "//what every you want concatenate".'.'.$image->getClientOriginalExtension(); //get the file extention
$destinationPath = public_path('/images'); //public path folder dir
$image->move($destinationPath, $name); //mve to destination you mentioned
$image->save(); //
}
}
Ответ 10
Это поможет вам. Загрузка изображений Laravel не является дефицитом. Если вы исполнили этот урок, вы сможете это сделать.
http://blog.airspaceteam.com/how-to-upload-images-using-laravelmysqlphp/
Ответ 11
В Laravel 5.4 вы можете использовать guessClientExtension