How can I upload image using Storage::put on the laravel? - laravel

My code to upload image like this :
$file = $file->move($path, $fileName);
The code works
But I want to change it using Storage::put like this reference :
https://laravel.com/docs/5.6/filesystem#storing-files
I try like this :
Storage::put($fileName, $path);
It does not works
I'm confused, where I must put $file on the code
How can I solve this problem?
Update :
$file = file of image
$path = storage_path('/app/public/product/')
$fileName = chelsea.jpg
So I want to save the file with name chelsea.jpg on the /app/public/product/

Easy Method
$path = $request->file('avatar')->storeAs(
'avatars', $request->user()->id
);
This will automatically store the files in your default configuration.
This is another example
Storage::put($fileName, $path);
Hope this helps

Related

Writing temp files

I am currently trying to display the sharepoint thumbnail in a picturebox when i click a button on the form. What appears to be happening is the file is locked and will not let me replace the file or anything. I even created a counter so the file name is always different. When I run the first time everything works, after that I believe it cant write over the file. Am I doing something wrong is there a better method??
$User=GET-ADUser $UserName –properties thumbnailphoto
$Filename='C:\Support\Export'+$Counterz+'.jpg'
#$img = $Filename.Open( [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::Read )
[System.Io.File]::WriteAllBytes($Filename, $User.Thumbnailphoto)
$Picture = (get-item ($Filename))
$img = [System.Drawing.Image]::Fromfile($Picture)
$pictureBox.Width = $img.Size.Width
$pictureBox.Height = $img.Size.Height
$pictureBox.Image = $img
$picturebox.dispose($Filename)
Remove-Item $Filename
You should be able to do this without creating a temporary file.
Just create $img like:
$img = [System.Drawing.Image]::FromStream([System.IO.MemoryStream]::new($User.thumbnailPhoto))
$pictureBox.Width = $img.Width
$pictureBox.Height = $img.Height
$pictureBox.Image = $img
Don't forget to remove the form from memory after closing with $form.Dispose()
If you insist on using a temporary file, then be aware that the $img object keeps a reference to the file untill it is disposed of.
Something like:
# get a temporary file name
$Filename = [System.IO.Path]::GetTempFileName()
[System.IO.File]::WriteAllBytes($Filename, $User.thumbnailPhoto)
# get an Image object using the data from the temporary file
$img = [System.Drawing.Image]::FromFile($Filename)
$pictureBox.Width = $img.Width
$pictureBox.Height = $img.Height
$pictureBox.Image = $img
$form.Controls.Add($pictureBox)
$form.ShowDialog()
# here, when all is done and the form is no longer needed, you can
# get rid of the $img object that still has a reference to the
# temporary file and then delete that file.
$img.Dispose()
Remove-Item $Filename
# clean up the form aswell
$form.Dispose()

How to write csv file and download in browser?

In laravel 5.7 app I need to write csv file and download in in browsers download function using method :
\Response::download(
I try to upload it to tmp directory and checking value I see
$sys_get_temp_dir= sys_get_temp_dir();
line above has /tmp value
Next I save it as :
$dest_csv_file= $sys_get_temp_dir . '/box_rooms_'.time().'.csv';
$header = ["Id",... ];
$fp = fopen($dest_csv_file, "w");
fputcsv($fp, $header);
foreach ($storageSpacesCollection as $line) {
fputcsv($fp, $line);
}
fclose($fp);
But searching on my local ubuntu 18(on server I also have ubuntu) I found generated file as
/tmp/systemd-private-6a9ea6844b9c4c94883d23e4fb3e2215-apache2.service-shqCeo/tmp/box_rooms_1576324869.csv
That was very strange, as I do not know how read it from tmp path. Can it be done?
I think you need to pass Content-Type properly
$filePath= public_path(). "/upload/example.doc";
$headersContent = array('Content-Type: application/pdf',);
return Response::download($filePath, 'example.doc', $headersContent)

How to get the uploaded image name from the store method

When I store an image in Laravel by doing:
$path = $request->file('myImage')->store('public/src/');
It returns the full path, but how do I get only the filename it was given?
This is an example of the returned path:
public/src/ltX4COwEmvxVqX4Lol81qfJZuPTrQO6S2jsicuyp.png
Here, you can try this one.
$fileNameWithExt = $request->file('myImage')->getClientOriginalName();
$fileNameWithExt = str_replace(" ", "_", $fileNameWithExt);
$filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
$filename = preg_replace("/[^a-zA-Z0-9\s]/", "", $filename);
$filename = urlencode($filename);
$extension = $request->file('myImage')->getClientOriginalExtension();
$fileNameToStore = $filename.'_'.time().'.'.$extension;
$path = $request->file('myImage')->storeAs('public/src/',$fileNameToStore);
return $fileNameToStore;
You will get your stored filename in $fileNameToStore.
Also, all the spaces will be replaced with "_" and you will get your stored filename with current time attached with it, which will help you differentiate between two files with the same name.
Since $path returns the full path to the saved file, it contains its generated name.
You have just to parse this string :
$extension = explode('/', $path);
$filename = end($extension)
which will give you ltX4COwEmvxVqX4Lol81qfJZuPTrQO6S2jsicuyp.png
In Laravel, the store() method generates the name dynamically .. so you can't get it from the store() method.
But you can use storeAs() method. Basically the store() method is calling the storeAs() method. So:
$path = $request->file('myImage')->store('public/src');
What Laravel is doing is calling ->storeAs('public/src', $request->file('myImage')->hashName()); .. you see the hashName() method? that is what generates the name.
So you can call hashName() first and know your name before the storing happens .. here is an example:
$uploadFile = $request->file('myImage');
$file_name = $uploadFile->hashName();
$path = $uploadFile->storeAs('public/src', $file_name);
Now you have $file_name and $path.
See:
https://laravel.com/docs/6.x/filesystem#file-uploads .. Specifying A File Name
https://github.com/laravel/framework/blob/6.x/src/Illuminate/Http/UploadedFile.php#L33
https://github.com/laravel/framework/blob/6.x/src/Illuminate/Http/FileHelpers.php#L42

Laravel 5.7 + Intervention Image : Image source not readable

I've create an app that upload image along with title, description & etc. However, i'm having a problem in some of the images to upload, it returns an error ("Image source not readable") as shown below:
Here's my Code:
$image = $request->file('image');
// $image = Input::file('image'); // already tried this one still same problem
$orginal_filename = $image->getClientOriginalName();
$ext = $image->getClientOriginalExtension();
$fileName = md5(microtime() . $orginal_filename) . '.' . $ext;
$img = Image::make($image->getRealPath());
$img->stream();
$img->resize(1200, null, function ($constraint) {
$constraint->aspectRatio();
});
Storage::disk('storage_dir')->put($dir . $fileName, $img, 'public');
Already tried following solutions:
Change to Input::file('file')
Check if Request Content-Type has multipart/form-data (Request already has multipart/form-data Content-Type)
Change Intervention Image driver from "gd" to "imagick"
but still have the "Image source not readable" error.
Note: Error only occurs in some images. (I've also tried moving the image(w/c produced the errors) into another directory but still error occurs).
Thank you so much for the help!
You can try running my code
if ($request->file('photo')->isValid()) {
$avatar = $request->file('photo');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->resize(300, 300)->save( public_path('/uploads/avatars/' . $filename) );
}
/uploads/avatars/ is my directory
If the problem occours in a Laravel 5.7 project, and you store your pictures in the storage folder, it might solve the problem to enter this into the terminal:
php artisan storage:link
(The problem occurs if you have cloned the project from github og bitbucket)
Sorry for bothering guys! It seemed that it was all my fault not realizing php post_max_size and php upload_max_file_size. Since i was trying to upload an image larger than 8MB i only increased the post_max_size > than the current image file size, but not the upload_max_file_size coz i only increased it by 2 (stated: 4MB).
Thanks btw for the help and suggestions!
Replace
$resize = Image::make('storage/app/public/'.$user->image)->resize(300,300);
with
$resize = Image::make(storage_path('app/public/'.$user->image))->resize(300,300);
Give storage full path will solve the problem.
If you got this error on your server, you need to be sure you pushed the all images to server. You are facing this error because of server could not find or read to image/images.
-> Be sure image/images uploaded
-> Make readable to image/images.

Error while uploading in Laravel 4

I'm trying to make a image upload in lavarel 4. The upload passes by
The file "C:\xampp\tmp\phpD1F3.tmp" does not exist
This is my upload code :
$file = Input::file('image');
// Get extension
$extension =$file->getClientOriginalExtension();
// Generate a file name
$fileName = 'pool' . Str::quickRandom();
$fileNameExtension = $fileName . '.' . $extension;
// Process upload
Input::file('image')->move(public_path() . '/uploads/images/app/pools/original/', $fileNameExtension);
`
I don't know why i get this error , please can anyone help me to solve this?
You are probably making some operations on "uploaded" file after moving it to server by move() function. Please make sure there is no operation made on temporary file after calling Input::file('image')->move() function.

Resources