Files not uploading due to unkown error using laravel - laravel

Laravel Version: 5.5
I have a problem when uploading a file. I have multiple files in the array, I am uploading these files two times in the same function for the first time I am checking pdf file version, and file dimensions this block of code works perfectly but in the second block of code I am again uploading these files for merging these files it gives me this error "The file "A4.pdf" was not uploaded due to an unknown error". When I remove the first block of code then the second block of code start working.I don't know where I did mistake, I have searched a lot but not found the answer.
This block of code checking pdf file version and dimensions.
$paper_size = array();
$del_files = array();
foreach ($files as $file) {
$filename = time().date('m-d-y').$file->getClientOriginalName();
$file->move(public_path().'/uploads/check_pdf_files/', $filename);
$version = $this->pdfVersion(public_path().'/uploads/check_pdf_files/'.$filename);
if($version > 1.5)
{
File::delete('public/uploads/check_pdf_files/'.$filename);
return Response::json(" Your PDF file version is greater than 1.4 which is not compatible with our system, Please make it lower version.", 400);
}
$get_paper_size = $this->get_pdf_dimensions('public/uploads/check_pdf_files/'.$filename);
$paper_size[] = $get_paper_size;
$del_files[] = $filename;
}
if(round($paper_size[0]['width']) != round($paper_size[1]['width']))
{
foreach ($del_files as $del)
{
File::delete('public/uploads/check_pdf_files/'.$del);
}
return Response::json(" Your Files dimensions is not matching please try with same dimensions.", 400);
}
This block of code using for merging the files.
$new_pdf_file = array();
foreach ($request->file as $merge_file)
{
$newFile_name = time().$merge_file->getClientOriginalName();
$merge_file->move('public/uploads/', $newFile_name);
$new_pdf_file[] = $newFile_name;
}
dd($new_pdf_file);
$pdf = new \LynX39\LaraPdfMerger\PdfManage;
foreach($new_pdf_file as $new)
{
$pdf->addPDF('public/uploads/dummy_uploads/'.$new, 'all');
}
$temp_name = time().$request->merge_name;
$pdf->merge('file',base_path(). '/public/uploads/' . Auth::user()->email . '/'.$temp_name.'.pdf', 'P');
foreach($new_pdf_file as $delete_new)
{
File::delete('public/uploads/dummy_uploads/'.$delete_new);
}
$user = DB::table('user_pdf_files')->insert([
'user_files' => $request->merge_name.'.pdf',
'filename' => $temp_name.'.pdf',
'type' => $request->type[0],
'user_id' => Auth::user()->id,
]);
Session::flash('success', 'Files Merged Successfully');
return Response::json('success', 200);`

You need the fully qualified path to where you want the files saved to. Anytime you are moving or copying a file, ensure that you are using public_path() with the relative path as a parameter. This function outputs the fully qualified path to the public folder. For example:
$merge_file->move(public_path('uploads'), $newFile_name);
This should be why the first code block is working vs. the second one. Not a very descriptive error, though!

Related

delete old image while updating the field

I am doing CRUD operations for images. when I am doing the update operation image gets updated but the old image doesn't delete. The following code updates only the file name in the database but I need to remove the old image from the destination folder too while updating else the folder size will become too large. Any ideas would be great. Here my code.
<input type="file" name="profileimage" value="{{ isset($editabout) ? $editabout->profileimage : '' }}" class="custom-file-input" id="exampleInputFile">
Here is my controller
public function update(updateAboutusProfile $request, AboutUs $about)
{
$data=$request->only(['profiletext']);
if($request->hasFile('profileimage')){
$profileimage = $request->profileimage->store('aboutus', 'public');
$oldimage = $about->profileimage;
Storage::delete($oldimage);
$data['profileimage'] = $profileimage;
}
$about->update($data);
toastr()->success('Profile updated successfully');
return redirect(route('about.index'));
//
}
What can be the error I need to resolve,
thank you
Try setting the disk you used to store the file
Storage::disk('public')->delete($oldimage);
Delete image from your server, you have to reference location of file in directory server, means you could not reference by url link to delete it.
Laravel file is locate in public folder.
Example: your files are located in public/images
$image_path = "/images/filename.ext"; // Value is not URL but directory file path
if(File::exists($image_path)) {
File::delete($image_path);
}
Enjoy ;)
You should save the path of the file to the database and then simply remove it using \Storage::delete() facade.
Store image using hash name
if($request->hasFile('profileimage')){
$store_path = 'aboutus';
$profileimage = $request->profileimage->store($store_path,'public');
$oldimage = $about->profileimage;
$file_address = $store_path.'/'.$request->profileimage->hashName();
\Storage::disk('public')->delete($oldimage);
$data['profileimage'] = $file_address;
}
Store image using original name
if($request->hasFile('profileimage')){
$store_path = 'aboutus';
$profileimage = $request->profileimage->storeAs($store_path, $uploadedFile->getClientOriginalName(),'public');
$oldimage = $about->profileimage;
$file_address = $store_path.'/'.$request->profileimage->getClientOriginalName();
\Storage::disk('public')->delete($oldimage);
$data['profileimage'] = $file_address;
}
Delete the old image while updating
public function update(Request $request, $id)
{
// other updates
if ($request->hasFile('image')) {
//delete old image if exist
if (File::exists(public_path($oldImage))) {
File::delete(public_path(oldImage));
}
//new image process
}
}

Laravel Excel handle error when file is open

I'm using Laravel Excel 2.1.0 in a local project to write a row into an excel file.
This is my code:
$filePath = storage_path('myfile.xls');
$rows = \Excel::load($filePath, function($reader) {
$sheet = $reader->sheet(0);
$sheet->appendRow(
array(
'Hello'
)
);
});
Everything works and a new line was appended to my file.
Sometimes can happens the excel file is opened while user try to append a new line. In this case Laravel, rightly, show me this error:
fopen(mypath\myfile.xls): failed to open stream: Resource temporarily unavailable
How can I handle this error in order to skip the function and go on with my code without append the row?
I solved in this way:
$filePath = storage_path('myfile.xls');
$fp = #fopen($filePath, "r+");
if($fp) {
$rows = \Excel::load($filePath, function($reader) {
$sheet = $reader->sheet(0);
$sheet->appendRow(
array(
'Hello'
)
);
});
}

Laravel 5.4 Storage : downloading files. File does not exist, but clearly it does

I have been going round and round with this. I have uploads working with the follow:
public function store(Tool $tool)
{
If(Input::hasFile('file')){
$file = Input::file('file');
$name = $file->getClientOriginalName();
$path=Storage::put('public',$file); //Storage::disk('local')->put($name,$file,'public');
$file = new File;
$file->tool_id = $tool->id;
$file->file_name = $name;
$file->path_to_file = $path;
$file->name_on_disk = basename($path);
$file->user_name = \Auth::user()->name;
$file->save();
return back();
}
however when I try to download with:
public function show($filename)
{
$url = Storage::disk('public')->url($filename);
///$file = Storage::disk('public')->get($filename);
return response()->download($url);
}
I get the FileNotFound exception from laravel
However, if I use this instead:
$file = Storage::disk('public')->get($filename);
return response()->download($file);
I get
FileNotFoundException in File.php line 37: The file "use calib;
insert into
notes(tool_id,user_id,note,created_at,updated_at)
VALUES(1,1,'windows server 2008 sucks',now(),now());" does not exist
which is the actual content of the file...
It can obviously find the file. but why wont it download?
Try this:
return response()->download(storage_path("app/public/{$filename}"));
Replace:
$file = Storage::disk('public')->get($filename);
return response()->download($file);
With:
return response()->download(storage_path('app/public/' . $filename));
response()->download() takes a path to a file, not a file content. More information here: https://laravel.com/docs/5.4/responses#file-downloads
If any one still could not find their file even though the file clearly exists then try
return response()->file(storage_path('/app/' . $filename, $headers));
It could be due to a missing directory separator or it isn't stored inside the public folder.

multiple file upload from postman in laravel

I am trying to upload multiple files but I only get 1 file in return.Below is my code:
public function uploadQuoteItemImage(){
$file=Input::file('filename');
$file_count=count($file);
dd($file_count);
$uploadcount=0;
foreach($file as $f){
$random_name=str_random(8);
$destinationPath='images/';
$extension=$file->getClientOriginalExtension();
$filename=$random_name.'_quote_itm_image.'.$extension;
$byte=File::size($file); //get size of file
$uploadSuccess=Input::file('filename')->move($destinationPath,$filename);
$uploadcount ++;
}
if ($uploadcount == $file_count){
QuoteItemImage::create(array(
'quote_item_id'=>Input::get('quote_item_id'),
'filename'=>$filename,
'filesize'=>$byte
));
return Common::getJsonResponse(true, 'image created', 200);
}
}
Even though I sent 3 files its returning only 1 file. Please help.
so in the form-data of postman you are giving the key attribute as filename for files
in turn it should be filename[] since you are sending array of data
once you set it it works fine .
now you can check in the php code like below
$files = Input::file('filename');
foreach ($files as $one) {
$filename = $one->getClientOriginalName();
$listfilenames[] = $filename;
}
echo $listfilenames

Laravel, Intervention, Corrupt JPEG data: 1130 extraneous bytes before marker 0xd9

so i give up. i have more forum windows open than i can count, have tried a bunch of different things and still no luck. i have installed intervention with laravel 5.0 and can get some images through but others (many) bomb out with the following error
ErrorException in Decoder.php line 35:
imagecreatefromjpeg(): gd-jpeg, libjpeg: recoverable error: Corrupt JPEG data: 1130 extraneous bytes before marker 0xd9
use Intervention\Image\ImageManager;
//use Intervention\Image\Image;
//use Intervention\Image\Facades\Image;
use Image;
public function storepic($id)
{
$gallry=auth()->user()->galleries()->findorfail($id);
$files = Input::file('images');
// Making counting of uploaded images
$file_count = count($files);
// start count how many uploaded
$uploadcount = 0;
ini_set('gd.jpeg_ignore_warning', true);
$dt=Carbon::now();
Carbon::setToStringFormat('omj_His');
foreach($files as $file) {
$rules = array('file' =>'required|mimes:png,gif,jpeg,jpg');
$d=array('file'=> $file);
$ext=$file->getClientOriginalExtension();
$mim=$file->getClientMimeType();
$validator = Validator::make($d, $rules);
if($validator->passes()){
//save file
$upPath = 'uploads/galleries/' . $id . '/';
$filename = $dt . $file->getClientOriginalName() ;
$upload_success = $file->move($upPath, $filename);
// save to db
$imag['oFileName']=$file->getClientOriginalName() ;
$imag['sFileName']=$filename;
$imag['gid']=$id;
$pic=new Pictures($imag);
$pic->save();
if ($gallry['img_id']==null){
$gallry['img_id']=$pic['pid'];
$gallry->save();
}
//create thumbnail
$path = 'uploads/thumbs/' . $id . '/';
// below used to all be one statement - it didn't effect it either way
$img= Image::make($upPath . $filename);
$img->resize(null, 100, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
$img->save($path . $filename);
$uploadcount ++;
}
}
so i've tried to
1. suppress the errors with
ini_set('gd.jpeg_ignore_warning', true);
in multiple places
2. recreate image with binary, which blew the image to 5x in size
3. tried createimagefromstring as opposed to jpeg
i'm thinking/wondering
-if i'm not suppressing errors correctly.
-is the problem with the gd library as opposed to imagick. i haven't added imagick yet, but can, it just seems like a pain
-i could try to do the resize in another procedure, but that just seems to be putting off the problem
any thoughts would be appreciated. thanks for your help!
I had the same well known problem. Adding the ini_set as the first line of the index.php didn't work in my case.
I ended up with a try catch solution, warning the user the JPG is damaged.
try {
$img = Image::make($filename);
} catch(\Exception $e) {
my_flash_message($e->message);
}
Take care Exception is namespaced so you have to use the slash.
Hope it helps.

Resources