I am migrating my existing PHP program to Laravel. I know the upload should be $request->files->store('images'); but this doesn't compress the images beforehand.
I have found Intervention Image plugin for Laravel but I don't want to use it because I want it to be pure PHP only.
My working code from pure PHP was:
$info = getimagesize($tmpFilename);
if ($info['mime'] == 'image/jpeg') {
$image = imagecreatefromjpeg($tmpFilename);
} else if ($info['mime'] == 'image/gif') {
$image = imagecreatefromgif($tmpFilename);
} else if ($info['mime'] == 'image/png') {
$image = imagecreatefrompng($tmpFilename);
}
imagejpeg($image, $path, 60);
I know the images get saved at /storage/app/public/ so I used that path for imagejpeg as well. This is my laravel code:
$tmp_file = $inner->getPathName();
imagejpeg($tmp_file, '/storage/app/public/images/hehe.jpg', 60);
But it doesn't work. It only says
imagejpeg(/storage/app/public/images/hehe.jpg): failed to open stream: No such file or directory
Any help would be appreciated
Related
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!
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.
We migrated the data(without files) to mLab and Heroku. So the old files are still on Parse.
Since then, any new file added goes into Gridstore, which is the default file storage for mLab.
Now I migrated old parse files from Parse to an S3 Bucket using sashido
The files are migrated and are accessible using S3Adapter in Heroku.
But the files on Gridstore are not accessible now. How can I migrate them to the same S3 bucket and change references in mLab?
Maybe you're interested in the solution I've tried. It's not a simple operation, but I migrated successfully 3 databases with my parse server configuration.
It's based in a PHP script (with the Parse PHP SDK) that runs through every object, it gets the file from Parse.com and sets it (with any of your adapter configuration) in your own server.
The script looks like:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
date_default_timezone_set('America/New_York');
$fileField = $argv[1];
$class = $argv[2];
require_once 'vendor/autoload.php';
use Parse\ParseObject;
use Parse\ParseQuery;
use Parse\ParseACL;
use Parse\ParsePush;
use Parse\ParseUser;
use Parse\ParseInstallation;
use Parse\ParseException;
use Parse\ParseAnalytics;
use Parse\ParseFile;
use Parse\ParseCloud;
use Parse\ParseClient;
$app_id = "******";
$rest_key = "******";
$master_key = "******";
ParseClient::initialize($app_id, $rest_key, $master_key);
ParseClient::setServerURL('http://localhost:1338/', 'parse');
$query = new ParseQuery($class);
$query->ascending("createdAt"); // it's just my preference
$query->exists($fileField);
$query->limit(1);
$count = $query->count();
for ($i = 0; $i < $count; $i = $i + 1) {
try {
$query->skip($i);
// get Entry
$entryWithFile = $query->first();
// get file
$parseFile = $entryWithFile->get($fileField);
// filename
$fileName = $parseFile->getName();
// if the file is hosted in Parse, do the job, otherwise continue with the next one
if (strpos($fileName, "tfss-") === false) {
echo "\nThis is already an internal file, skipping...";
continue;
}
$newFileName = str_replace("tfss-", "", $fileName);
$binaryFile = file_get_contents($parseFile->getURL());
$newFile = ParseFile::createFromData($binaryFile, $newFileName);
$entryWithFile->set($fileField, $newFile);
$entryWithFile->save(true);
echo "\nFile saved\n";
}
catch (Exception $e) {
// The conection with mongo or the server could be off for some second, let's retry it ;)
sleep(10);
continue;
}
}
echo "\n";
echo "END!";
?>
set your parse url correctly.
Imagine you want to migrate the file from class _User with field imageProfile, so be sure that you pass $fileField = "imageProfile"; $class = "_User".
Run that code for any field per class.
I did a dumb solution to work in parallel, which would be skipping steps in the for loop, for example:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
date_default_timezone_set('America/New_York');
$index = $argv[1];
$of = $argv[2];
$fileField = $argv[3];
$class = $argv[4];
require_once 'vendor/autoload.php';
use Parse\ParseObject;
use Parse\ParseQuery;
use Parse\ParseACL;
use Parse\ParsePush;
use Parse\ParseUser;
use Parse\ParseInstallation;
use Parse\ParseException;
use Parse\ParseAnalytics;
use Parse\ParseFile;
use Parse\ParseCloud;
use Parse\ParseClient;
$app_id = "********";
$rest_key = "********";
$master_key = "********";
ParseClient::initialize($app_id, $rest_key, $master_key);
ParseClient::setServerURL('http://localhost:1338/', 'parse');
$query = new ParseQuery($class);
$query->ascending("createdAt");
$query->exists($fileField);
$query->limit(1);
$count = $query->count();
for ($i = $index; $i < $count; $i = $i + $of) {
try {
$query->skip($i);
// get Entry
$entryWithFile = $query->first();
// get file
$parseFile = $entryWithFile->get($fileField);
// filename
$fileName = $parseFile->getName();
// if the file is hosted in Parse, do the job, otherwise continue with the next one
if (strpos($fileName, "tfss-") === false) {
echo "\nThis is already an internal file, skipping...";
continue;
}
$newFileName = str_replace("tfss-", "", $fileName);
$binaryFile = file_get_contents($parseFile->getURL());
$newFile = ParseFile::createFromData($binaryFile, $newFileName);
$entryWithFile->set($fileField, $newFile);
$entryWithFile->save(true);
echo "\nFile saved\n";
}
catch (Exception $e) {
// The conection with mongo or the server could be off for some second, let's retry it ;)
sleep(10);
continue;
}
}
echo "\n";
echo "END!";
?>
so if you configure $fileField and $class as before, and you can open 3 threads and run:
php migrator.php 0 3 "imageProfile" "_User"
php migrator.php 1 3 "imageProfile" "_User"
php migrator.php 2 3 "imageProfile" "_User"
so you will have loops running like:
object 0, 3, 6
object 1, 4, 7
object 2, 5, 8
Good luck, and be quick! It's going to shut down in a few days.
error in exporting to pdf. i tried composer update and adding stuffs to app.php anf composer.json
public function exportPDF($request, $orgid)
{
/*$pdf = App::make('snappy.pdf.wrapper');
$pdf->loadHTML('<h1>Test</h1>');
return $pdf->inline();*/
$data = User::get()->toArray();
return Excel::create('itsolutionstuff_example', function($excel) use ($data) {
$excel->sheet('mySheet', function($sheet) use ($data)
{
$sheet->fromArray($data);
});
})->download("pdf");
}
Wich pdf renderer have you set up? Acording to the documentation, you have 3 choices, tcpdf, mPdf and DomPDF.
You have to install at least one of them.
composer require mpdf/mpdf
and then direct PHPExcel to use it
$renderer = PHPExcel_Settings::PDF_RENDERER_MPDF;
$rendererPath = dirname(__FILE__).'/../../../libraries/PDF/mPDF6.1'
if (!PHPExcel_Settings::setPdfRenderer(
$renderer,
$rendererPath
)) {
die('Wrong setup of PDF libraries');
}
Please comment this line in DomPDF.php
if (file_exists($pdfRendererClassFile)) {
require_once $pdfRendererClassFile;
} else {
throw new PHPExcel_Writer_Exception('Unable to load PDF Rendering library');
}
to
/** Require DomPDF library */
//$pdfRendererClassFile = PHPExcel_Settings::getPdfRendererPath() . '/dompdf_config.inc.php';
//if (file_exists($pdfRendererClassFile)) {
// require_once $pdfRendererClassFile;
//} else {
// throw new PHPExcel_Writer_Exception('Unable to load PDF Rendering library');
//}
Hope it will works.
I'm using intervention/image module with laravel 4.2 , to upload images i'm using this code :
if (Input::hasFile('image'))
{
$file = Input::file('image');
$file->move('uploads/2/', $file->getClientOriginalName());
$image = Image::make(sprintf('uploads/2/%s', $file->getClientOriginalName()))->resize(120, 120)->save();
return 'yes';
}
With some images it works , with some images it produces this error :
imagecreatefromjpeg(): gd-jpeg, libjpeg: recoverable error: Premature end of JPEG file
switch ($info[2]) {
case IMAGETYPE_PNG:
$core = imagecreatefrompng($path);
$this->gdResourceToTruecolor($core);
break;
case IMAGETYPE_JPEG:
$core = imagecreatefromjpeg($path);
$this->gdResourceToTruecolor($core);
break;
This is because you upload corrupted images and GD can't handle that kind of images. Please check it in this issue .
Try to suppress this error like this.
ini_set('gd.jpeg_ignore_warning', true);
Hope it will be useful for you.