Laravel 5.8 image failed to upload - laravel

I cannot seem to upload an image file with Laravel. I keep getting the photo failed to upload.
My form:
<form id="save_report_form" action="{{ route('report.add') }}" method="post" enctype="multipart/form-data">
<input type="file" name="image" class="upload-photo" id="image" accept="image/png,image/jpg" />
</form>
My Controller:
public function add(Request $request)
{
$this->validate($request, [
'image' => 'required|image|mimes:png,jpg',
]);
// Get all file details and store in public
$disk = Storage::disk('public');
$file = $request->file('image');
$ext = $file->getClientOriginalExtension();
$filename = $file . '.' . $ext;
$disk->put($filename, file_get_contents($file), 'public');
return redirect()->back();
}
I have changed upload_max_filesize to 20mb for my dev server.
Where can I look to find the reason for the upload failure? I am not getting anything in the Laravel log. What have I missed. Thanks.

can you replace
$filename = $file . '.' . $ext;
with
$filename = $request->image->getClientOriginalName();

You can check what is the result of $filename with dd() /dd($filename) function and see if it is what you expect. If it is not, probably there is the problem.
Also as far as i see in the official docs(https://laravel.com/docs/5.8/filesystem#file-visibility) the usage of put() method is exampled without php native file_get_contents(check this also).

Related

Ckeditor upload picture in laravel project

I have integrated ckeditor in my laravel project, and when i try add a picture in the text after i click on save post. I Get an error in the console. POST https://encode.ba/admin/lista-vijestis/4 403 (Forbidden)
The upload working fine, permission on the storage folder is set properly
and of course, don't record my post
it seems to me that the server is blocking something, I'm not sure, that's why I'm asking, maybe someone has a similar experience
I downloaded the project to my computer and ran it on a local server and everything works fine.
here is a screenshot
enter image description here
enter image description here
Here is first screen shot when i try add post.
In your html page:
<textarea name="description" placeholder="Enter the Description"></textarea>
In script:
<script src="https://cdn.ckeditor.com/4.12.1/standard/ckeditor.js"></script>
<script>
CKEDITOR.replace('description', {
filebrowserUploadUrl: "{{ route('admin.product.uploadMedia', ['_token' => csrf_token()]) }}",
filebrowserUploadMethod: 'form'
});
</script>
create Route:
Route::post('product/img', [ProductController::class, 'uploadMedia'])->name('admin.product.uploadMedia');
In Controller:
public function uploadMedia(Request $request)
{
if ($request->hasFile('upload')) {
$originName = $request->file('upload')->getClientOriginalName();
$fileName = pathinfo($originName, PATHINFO_FILENAME);
$extension = $request->file('upload')->getClientOriginalExtension();
$fileName = $fileName . '_' . time() . '.' . $extension;
$path = storage_path('app/public/tmp/uploads');
$fileName = $request->file('upload')->move($path, $fileName)->getFilename();
$CKEditorFuncNum = $request->input('CKEditorFuncNum');
$url = asset('storage/tmp/uploads/' . $fileName);
$msg = 'Image uploaded successfully';
$response = "<script>window.parent.CKEDITOR.tools.callFunction($CKEditorFuncNum, '$url', '$msg')</script>";
#header('Content-type: text/html; charset=utf-8');
echo $response;
}
return false;
}

Uploading files with infyom generator

I am trying to upload a file with laravel using the code generated by the infyom generator. The file seems to be uploaded but this is what is shown on the application when I view the report (C:\xampp\tmp\php7925.tmp). Provided below is the code for my application.
Thank you so much and really appreciate the help in this project.
rgds,
Form
<!-- Inf File Field -->
<div class="form-group col-sm-6">
{!! Form::label('inf_file', 'Attachments:') !!}
{!! Form::file('inf_file') !!}
</div>
Controller
{
$input = $request->all();
$infrastructure = $this->infrastructureRepository->create($input);
$file = $request->file('inf_file');
$file = $request->inf_file;
if ($request->hasFile('inf_file')){
//
if ($request->file('inf_file')->isValid()){
}
}
Flash::success('Infrastructure saved successfully.');
return redirect(route('infrastructures.index'));
}
This is how you display when you view your records,
<!-- Inf File Field -->
<div class="form-group">
{!! Form::label('inf_file', 'Attachements:') !!}
<a download href="{{ asset($infrastructure->inf_file) }}">Download</a>
</div>
Managed to solve it.
public function store(CreateinfrastructureRequest $request)
{
$input = $request->all();
if ($request->hasFile('inf_file')){
//Validate the uploaded file
$Validation = $request->validate([
'inf_file' => 'required|file|mimes:pdf|max:30000'
]);
// cache the file
$file = $Validation['inf_file'];
// generate a new filename. getClientOriginalExtension() for the file extension
$filename = 'Infras-' . time() . '.' . $file->getClientOriginalExtension();
// save to storage/app/infrastructure as the new $filename
$InfrasFileName = $file->storeAs('infrastructure', $filename);
$path = "/storage/app/public/".$InfrasFileName;
}
$input['inf_file'] = $path;
$infrastructure = $this->infrastructureRepository->create($input);
Flash::success('Infrastructure saved successfully. ' . $path);
return redirect(route('infrastructures.index'));
}

The "" file does not exist or is not readable

I am having some issue while trying to upload multiple images on the back end in Laravel. I have a simple form with an input field and a multiple attribute that should upload an array of images in the database but whatever I try, I get the same error 'The "" file does not exist or is not readable'. I checked the names in the input field and they are the same as the name in the file() method. Any help is appreciated.
PS: Am a newbie to Laravel and PHP...
ProductController:
foreach($request->file('images')->store('images') as $images) {
$product->images()->create([
'images' => $images
]);
}
Blade file:
<form method="POST" enctype="multipart/form-data">
#csrf
<h5>Upload Multiple Images</h5>
<input type="file" multiple name="images" id="images"> Upload Images
</form
I know this is an old question, but I had the same issue a few days ago. Hope this helps anyone.
I solved the problem by setting php_value upload_max_filesize in php.ini over the size of my uploaded file.
This is where I found the answer in case you are interested:
If someone else gets this error and it doesn't turn out to be a permissions issue, check your php.ini...make sure that your upload_max_filesize is as big as your post_max_size. I had 1000M for post_max_size (we deal with some big ol' video files), but only 100M for upload_max_size (I blame my old eyes). The upload would churn for a long time, and then throw the error above.
https://github.com/laravel/framework/issues/31249
Try..
$input = $request->all();
$datas = [];
if ($request->hasfile('images')) {
foreach ($request->file('images') as $key => $file) {
$name = $file->getClientOriginalName();
$file->move(public_path() . '/your path /', $name); //if you want to store image in yopur folder
$datas[$key] = $name;
$file = new YourMOdelNAme();
foreach ($datas as $data) {
$file->images = $data;
$file->save();
}
}
}
name images array
<form method="POST" enctype="multipart/form-data">
#csrf
<h5>Upload Multiple Images</h5>
<input type="file" multiple name="images[]" id="images"> Upload Images
</form
Upload files using below code
$files = $request->file('images');
if($request->hasFile('images'))
{
foreach ($files as $file)
$product->images()->create([
'images' => $file
]);
}

Laravel Retrieve Images from storage to view

I am using below code to store the uploaded file
$file = $request->file($file_attachment);
$rules = [];
$rules[$file_attachment] = 'required|mimes:jpeg|max:500';
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
return redirect()->back()
->with('uploadErrors', $validator->errors());
}
$userid = session()->get('user')->id;
$destinationPath = config('app.filesDestinationPath') . '/' . $userid . '/';
$uploaded = Storage::put($destinationPath . $file_attachment . '.' . $file->getClientOriginalExtension(), file_get_contents($file->getRealPath()));
The uploaded files are stored in storage/app/2/filename.jpg
I want to show back the user the file he uploaded. How can i do that?
$storage = Storage::get('/2/filename.jpg');
I am getting unreadable texts. I can confirm that the file is read. But how to show it as an image to the user.
Hope i made my point clear.
Working Solution
display.blade.php
<img src="{{ URL::asset('storage/photo.jpg') }}" />
web.php
Route::group(['middleware' => ['web']], function () {
Route::get('storage/{filename}', function ($filename) {
$userid = session()->get('user')->id;
return Storage::get($userid . '/' . $filename);
});
});
Thanks to: #Boghani Chirag and #rkj
File not publicly accessible like you said then read file like this
$userid = session()->get('user')->id;
$contents = Storage::get($userid.'/file.jpg');
Assuming your file is at path storage/app/{$userid}/file.jpg
and default disk is local check config/filesystems.php
File publicly accessible
If you want to make your file publicly accessible then store file inside this storage/app/public folder. You can create subfolders inside it and upload there. Once you store file inside storage/app/public then you have to just create a symbolic link and laravel has artisan command for it.
php artisan storage:link
This create a symbolic link of storage/app/public to public/storage. Means now you can access your file like this
$contents = Storage::disk('public')->get('file.jpg');
here the file physical path is at storage/app/public/file.jpg and it access through symbolic link path public/storage/file.jpg
Suppose you have subfolder storage/app/public/uploads where you store your uploaded files then you can access it like this
$contents = Storage::disk('public')->get('uploads/file.jpg');
When you make your upload in public folder then you can access it in view
echo asset('storage/file.jpg'); //without subfolder uploads
echo asset('storage/uploads/file.jpg');
check for details https://laravel.com/docs/5.6/filesystem#configuration
Remember put your folder in storage/app/public/
Create the symbolic linksymbolic link to access this folder
php artisan storage:link
if you want to access profile images of 2 folder then do like this in your blade file
<img src="{{ asset('storage/2/images/'.$user->profile_image) }}" />
Laravel 8
Controller
class MediaController extends Controller
{
public function show(Request $request, $filename)
{
$folder_name = 'upload';
$filename = 'example_img.jpeg';
$path = $folder_name.'/'.$filename;
if(!Storage::exists($path)){
abort(404);
}
return Storage::response($path);
}
}
Route
Route::get('media/{filename}', [\App\Http\Controllers\MediaController::class, 'show']);
Can you please try this code
routes.php
Route::group(['middleware' => ['web']], function() {
Route::get('storage/storage_inner_folder_fullpath/{filename}', function ($filename) {
return Image::make(storage_path() . '/storage_inner_folder_fullpath/' . $filename)->response();
});
});
view file code
<img src="{{ URL::asset('storage/storage_inner_folder_fullpath/'.$filename) }}" />
Thanks
Try this:
Storage::disk('your_disk_name')->getDriver()->getAdapter()->applyPathPrefix('your_file_name');
Good Luck !
Uploaded like this
$uploadedFile = $request->file('photo');
$photo = "my-prefix" . "_" . time() . "." . $uploadedFile->getClientOriginalExtension();
$photoPath = \Illuminate\Support\Facades\Storage::disk('local')->putFileAs(
"public/avatar",
$uploadedFile,
$photo
);
and then access like this
<img src="{{ asset('storage/avatar/'.$filename) }}" />
Create Route:
Route::get('image/{filename}', 'HomeController#displayImage')->name('image.displayImage');
Create Controller Method:
public function displayImage($filename)
{
$path = storage_public('images/' . $filename);
if (!File::exists($path)) {
abort(404);
}
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
return $response;
}
<img src="{{ route('image.displayImage',$article->image_name) }}" alt="" title="">
can You please try this
$storage = Storage::get(['type_column_name']);

How to Upload an Image in Laravel 5

I am new to Laravel 5. Actually I'm using Laravel Framework version 5.1.16. When uploading an image, it is uploading and saved in database table, but it is not moved to a specified folder.
Any help would be appreciated.
This is my controller code:
public function addexpense(Request $request) {
$inputs=Input::all();
$validation = Validator::make($inputs, Expense::$rules);
if($validation->fails()) {
return Redirect::to('expenseaddform')->withErrors($validation)->withInput();
}else{
$input=Input::only('id','expense_date','expense_category_id','vendor_id','customer_id','amount','tax1_id','tax2_id','note','receipt');
$data->expense_date = $input['expense_date'];
$data->expense_category_id = $input['expense_category_id'];
$data->vendor_id = $input['vendor_id'];
$data->customer_id = $input['customer_id'];
$data->amount = $input['amount'];
$data->tax1_id = $input['tax1_id'];
$data->tax2_id = $input['tax2_id'];
$data->note = $input['note'];
$image = Input::file('receipt');
$filename = date('Y-m-d-H:i:s')."-".$image->getClientOriginalName();
Image::make($image->getRealPath())->resize(468, 249)->save('public/uploas/'. $filename);
$data->receipt = $input['image'];
$data->save();
return redirect('expenseinfo');
}
}
Form code:
<form action="addexpense" enctype="multipart/form-data" >
Receipt:</td><td><input type="file" name="receipt"value="{{Input::old('receipt')}}">
<input style="margin-left:30px"type="submit" value="Add" name="submit">
</form>
You are doing it wrong with Image::make() function. Try the following:
Image::make($image->getRealPath())->resize(468, 249)->save(public_path() . '/uploads/' . $filename);
Try this:
Image::make($image->getRealPath())->resize(468, 249)->save(public_path('uploads/'). $filename);
For more information you can check the below link:
https://youtu.be/F92JpVWhDw4

Resources