Why my .jpg files are saved as .tmp? - laravel

I am following a tutorial from Laracasts, for uploading files. Here in the example I will upload a jpg file or png file, and in my images folder I get a file with different name and with a different extension. Why is that?
This is how I am moving the uploaded file.
And here is how the files are saved.

You better send also the filename:
Input::file('photo')->move($destinationPath, $fileName);
You'll probably be able to (not tested)
Input::file('photo')->move($destinationPath, Input::file('photo')->getClientOriginalName());
Also, check the docs: http://laravel.com/docs/requests#files

You may try this (No need to use public_path):
public function store()
{
$targetPath = 'images'; // For "public/images"
$file = Input::file('image'); // If "image" is the name of the file input
$filename = $file->getClientOriginalName();
$file->move($targetPath, $fileName);
}

Related

Safety in laravel file upload

I have a simple question.. Is it safe to have a app that has a file upload system for users to send images to our project, and store those files in this directory?
$file->move(public_path('../storage/app/public/files'), $name);
Or is it better to store in:
$file->move(public_path('files'), $name);
This way it stores the file in the "files" directory inside the public directory.
That would be ok and also depends on your app and number of users but I recommend to change the name of the file and also you can accept only JPG or PNG file for more security for changing the name of the file you can do it like this :
$image_name = rand() . '.' . $image->getClientOriginalExtension();
$image->move(public_path('images'), $image_name);
with this function you can get all data from db for that id then you can show whatever you want in the blade
public function show($id)
{
$data = YOUR_MODEL::findOrFail($id);
return view('view', compact('data'));
}

How to delete photo from project's public folder before updating data in lumen/laravel?

I am trying to delete photo from my projects public folder before updating another photo. My code looks like-
if(File::exist( $employee->avatar)){
//$employee->avatar looks /uploads/avatars/1646546082.jpg and it exist in folder
File::delete($employee->avatar);
}
This is not working in my case. If I comment these code then another photo updated without deleting perfectly. How can I solve the issue!
try php unlink function
$path = public_path()."/pictures/".$from_database->image_name;
unlink($path);
This is the code which i use in update profile picture you can do this exactly like this
$data=Auth::user();
if($request->hasFile('image')){
$image = $request->file('image');
$filename = 'merchant_'.time().'.'.$image->extension();
$location = 'asset/profile/' . $filename;
Image::make($image)->save($location);
$path = './asset/profile/';
File::delete($path.$data->image);
$in['image'] = $filename;
$data->fill($in)->save();
}

how to save dompdf file to storage and name the file dynamicly in laravel

does anyone know how to save generated pdf file and name it dynamicly using dompdf in laravel?
i always encounter this error
failed to open stream: No such file or directory
while trying to generated pdf file and save it to project directory.
here its my controller code
$bills = Tagihan::join('pesanan', 'tagihan.id_pesanan', 'pesanan.id_pesanan')
->join('kendaraan', 'pesanan.id_kendaraan', 'kendaraan.id_kendaraan')
->join('kategori_mobil', 'kendaraan.id_kategori_kendaraan', 'kategori_mobil.id_kategori')
->join('users', 'pesanan.id_pengguna', 'users.id')
->where('pesanan.id_pesanan', $save->id_pesanan)
->select('pesanan.*', 'users.*', 'tagihan.*', 'kendaraan.*', 'kategori_mobil.nama_kategori')
->first();
$today = Carbon::now('GMT+7')->toDateString();
$pdf = new PDF();
$pdf = PDF::loadView('admin.tagihan.pdf', compact('bills','today'));
file_put_contents('public/bills/'.$noOrder.'.pdf', $pdf->output() );
return redirect()->route('pesananIndex');
i want to save my pdf file with custom string with $noOrder.'pdf', but when i use static name like this
file_put_contents('public/bills/bubla.pdf', $pdf->output());
i had no error, any solution?
You can getOriginalContent from http response into a variable then push it to your file.
$pdf = PDF::loadView('admin.tagihan.pdf', compact('bills','today'));
$content = $pdf->download()->getOriginalContent();
Storage::put('public/bills/bubla.pdf',$content);
...
Storage::disk('local')->makeDirectory('/pdf/order');
$pdf = PDF::loadView('PDF.Order.OrderPDF-dev', ['invoiceDetail'=>$invoiceDetail]);
$path = 'storage/pdf/order/';
$pdf->save($path . $fileName);
return url($path.$fileName);
In my example first i created folder for PDF. makeDirectory(...) will create folder if exist or not.
$path is location where i want to put my file in Dir. do not use absolute path or public path function here. only define location where you want to create file.
I am creating file in Storage folder. so i added storage/.....

Laravel : To rename an uploaded file automatically

I am allowing users to upload any kind of file on my page, but there might be a clash in names of files. So, I want to rename the file automatically, so that anytime any file gets uploaded, in the database and in the folder after upload, the name of the file gets changed also when other user downloads the same file, renamed file will get downloaded.
I tried:
if (Input::hasFile('file')){
echo "Uploaded</br>";
$file = Input::file('file');
$file ->move('uploads');
$fileName = Input::get('rename_to');
}
But, the name gets changed to something like:
php5DEB.php
phpCFEC.php
What can I do to maintain the file in the same type and format and just change its name?
I also want to know how can I show the recently uploaded file on the page and make other users download it??
For unique file Name saving
In 5.3 (best for me because use md5_file hashname in Illuminate\Http\UploadedFile):
public function saveFile(Request $request) {
$file = $request->file('your_input_name')->store('your_path','your_disk');
}
In 5.4 (use not unique Str::random(40) hashname in Illuminate\Http\UploadedFile). I Use this code to ensure unique name:
public function saveFile(Request $request) {
$md5Name = md5_file($request->file('your_input_name')->getRealPath());
$guessExtension = $request->file('your_input_name')->guessExtension();
$file = $request->file('your_input_name')->storeAs('your_path', $md5Name.'.'.$guessExtension ,'your_disk');
}
Use this one
$file->move($destinationPath, $fileName);
You can use php core function rename(oldname,newName) http://php.net/manual/en/function.rename.php
Find this tutorial helpful.
file uploads 101
Everything you need to know about file upload is there.
-- Edit --
I modified my answer as below after valuable input from #cpburnz and #Moinuddin Quadri. Thanks guys.
First your storage driver should look like this in /your-app/config/filesystems.php
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'), // hence /your-app/storage/app/public
'visibility' => 'public',
],
You can use other file drivers like s3 but for my example I'm working on local driver.
In your Controller you do the following.
$file = request()->file('file'); // Get the file from request
$yourModel->create([
'file' => $file->store('my_files', 'public'),
]);
Your file get uploaded to /your-app/storage/app/public/my_files/ and you can access the uploaded file like
asset('storage/'.$yourModel->image)
Make sure you do
php artisan storage:link
to generate a simlink in your /your-app/public/ that points to /your-app/storage/app/public so you could access your files publicly. More info on filesystem - the public disk.
By this approach you could persists the same file name as that is uploaded. And the great thing is Laravel generates an unique name for the file so there could be no duplicates.
To answer the second part of your question that is to show recently uploaded files, as you persist a reference for the file in the database, you could access them by your database record and make it ->orderBy('id', 'DESC');. You could use whatever your logic is and order by descending order.
You can rename your uploaded file as you want . you can use either move or storeAs method with appropiate param.
$destinationPath = 'uploads';
$file = $request->file('product_image');
foreach($file as $singleFile){
$original_name = strtolower(trim($singleFile->getClientOriginalName()));
$file_name = time().rand(100,999).$original_name;
// use one of following
// $singleFile->move($destinationPath,$file_name); public folder
// $singleFile->storeAs('product',$file_name); storage folder
$fileArray[] = $file_name;
}
print_r($fileArray);
correct usage.
$fileName = Input::get('rename_to');
Input::file('photo')->move($destinationPath, $fileName);
at the top after namespace
use Storage;
Just do something like this ....
// read files
$excel = $request->file('file');
// rename file
$excelName = time().$excel->getClientOriginalName();
// rename to anything
$excelName = substr($excelName, strpos($excelName, '.c'));
$excelName = 'Catss_NSE_'.date("M_D_Y_h:i_a_").$excelName;
$excel->move(public_path('equities'),$excelName);
This guy collect the extension only:
$excelName = substr($excelName, strpos($excelName, '.c'));
This guy rename its:
$excelName = 'Catss_NSE_'.date("M_D_Y_h:i_a_").$excelName;

Laravel 4 get image from url

OK so when I want to upload an image. I usually do something like:
$file = Input::file('image');
$destinationPath = 'whereEver';
$filename = $file->getClientOriginalName();
$uploadSuccess = Input::file('image')->move($destinationPath, $filename);
if( $uploadSuccess ) {
// save the url
}
This works fine when the user uploads the image. But how do I save an image from an URL???
If I try something like:
$url = 'http://www.whereEver.com/some/image';
$file = file_get_contents($url);
and then:
$filename = $file->getClientOriginalName();
$uploadSuccess = Input::file('image')->move($destinationPath, $filename);
I get the following error:
Call to a member function move() on a non-object
So, how do I upload an image from a URL with laravel 4??
Amy help greatly appreciated.
I don't know if this will help you a lot but you might want to look at the Intervention Library. It's originally intended to be used as an image manipulation library but it provides saving image from url:
$image = Image::make('http://someurl.com/image.jpg')->save('/path/saveAsImageName.jpg');
$url = "http://example.com/123.jpg";
$url_arr = explode ('/', $url);
$ct = count($url_arr);
$name = $url_arr[$ct-1];
$name_div = explode('.', $name);
$ct_dot = count($name_div);
$img_type = $name_div[$ct_dot -1];
$destinationPath = public_path().'/img/'.$name;
file_put_contents($destinationPath, file_get_contents($url));
this will save the image to your /public/img, filename will be the original file name which is 123.jpg for the above case.
the get image name referred from here
Laravel's Input::file method is only used when you upload files by POST request I think. The error you get is because file_get_contents doesn't return you laravel's class. And you don't have to use move() method or it's analog, because the file you get from url isn't uploaded to your tmp folder.
Instead, I think you should use PHP upload an image file through url what is described here.
Like:
// Your file
$file = 'http://....';
// Open the file to get existing content
$data = file_get_contents($file);
// New file
$new = '/var/www/uploads/';
// Write the contents back to a new file
file_put_contents($new, $data);
I can't check it right now but it seems like not a bad solution. Just get data from url and then save it whereever you want

Resources