My controller code for upload file in 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) {
}
}
}
Image was successfully uploaded but the code threw an exception :
FileNotFoundException in MimeTypeGuesser.php line 123
The file is there any fault in my code or is it a bug in laravel 5.4, can anyone help me solve the problem ?
My view code:
<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>
Try this code. This will solve your problem.
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');
}
}
You can use it by easy way, through store
method in your controller
like the below
{{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);
}
}
That’s it. Now you can save the $photoName
to the database as a user_photo
field value. You can use asset(‘avatars’)
function in your view and access the photos.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With