Upload File/Image with class Storage Laravel 5.2 - php

First, I'm sorry for my bad English.
I want to upload a file/image from my driver to my project directory using class Storage. I want that every file/image will be uploaded/moved to my public/img directory. I use Form::file('img') on my views and on my post controller, I write this
$img = Input::file('img');
if ($img !== null) {
$filename = $img->getClientOriginalName();
Storage::disk('uploads')->put('filename', $filename);
$jenis->img = $filename;
}
and on my config/filesystem I write this
'uploads' => [
'driver' => 'local',
'root' => public_path() . '/img',
],
But, nothing happen on my public/img directory, no new file/image on there.
Can u help me whats wrong with my code?
and I hope u guys can help me with another good way on how to upload a file/image in laravel

Looks like your problem is you're not storing the file, you're referencing its name not its contents.
Try this:
Storage::disk('uploads') -> put($filename, file_get_contents($img -> getRealPath()));

In my filesystem file I configure my image directory in this way:
'uploads' => [
'driver' => 'local',
'root' => public_path("/img"),
],
I think that you can use your way but is another point.
To get the file from your view you should use File::get Laravel function:
$filename = $img->getClientOriginalName();
Storage::disk('uploads')->put($filename, \File::get($file));
With this would be enough, you save the file with the name of file uploaded in directory specify in filesystem.

if ($request->hasFile('original_pic')) {
$original_pic = $request->file('original_pic');
$file_extension=$original_pic>getClientOriginalExtension();
$filename = time() . '.' . $file_extension;
# upload original image
Storage::put('ArticlesImages/' . $filename, (string) file_get_contents($original_pic), 'public');
# croped image from request.
$image_parts = explode(";base64,", $request->input('article_image'));
$image_base64 = base64_decode($image_parts[1]);
Storage::put('ArticlesImages/croped/' . $filename, (string) $image_base64, 'public');
# get image from s3 or local storage.
$image_get = Storage::get('ArticlesImages/croped/' . $filename);
# resize 50 by 50 1x
$image_50_50 = Image::make($image_get)
->resize(340, 227)
->encode($file_extension, 80);
Storage::put('ArticlesImages/1x/' . $filename, (string) $image_50_50, 'public');
$file_url = Storage::url('ArticlesImages/croped/' . $filename);
return response()->json(['success' => true, 'filename' => $filename, 'file_url' => $file_url], 200);
}

Related

How to retrieve uploaded file from a custom file system in Laravel?

I have uploaded a file to my custom file system and it just works.
Custom File System:
'private' => [
'driver' => 'local',
'root' => storage_path('app/private'),
],
This is how I upload my files:
if ($request->hasFile('chatattachment')) {
$file = request()->file('chatattachment');
$fname = date('YmdHis');
$ext = $request->chatattachment->extension();
$filename = $fname . '.' . $ext;
$file->storeAs('attachments', $filename, ['disk' => 'private']);
//Trying to get the url but it doest work:
$url = Storage::url('private/attachments/' . $filename);
}
Now, What I'm trying to do is to get the url of the newly uploaded image and return it back to the front end side. How to make it possible? I know how to create a storage:link but I don't want to expose this attachments to the public.

error 403 forbidden, when I upload image in laravel 5.8

I testing a code for upload image on laravel 5.8 local and I uploaded image unsuccessful then I recieved error 403 forbidden.
public function store(Request $request)
{
request()->validate([
'profile_image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if ($files = $request->file('profile_image')) {
// Define upload path
$destinationPath = public_path('/profile_images/'); // upload path
// Upload Orginal Image
$profileImage = date('YmdHis') . "." . $files->getClientOriginalExtension();
$files->move($destinationPath, $profileImage);
$insert['image'] = "$profileImage";
// Save In Database
$imagemodel= new Photo();
$imagemodel->photo_name="$profileImage";
$imagemodel->save();
}
return back()->with('success', 'Image Upload successfully');
}
I followed above code on internet and I don't know where I wrong. I need help !
Thank you.
Have you tried php artisan storage:link
Try this code format just change variable name
Try this on your project folder
chmod -R 777
$request->validate([
'profile_image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$fileNameWithExt = $request->file('profile_image')->getClientOriginalName();
$ext = $request->file('profile_image')->getClientOriginalExtension();
$fileNameWithoutExt = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
$fileNameToStore = $fileNameWithoutExt . time() . "." . $ext;
$path = $request->file('profile_image')->storeAs('public/profile_images', $fileNameToStore);
$addPhoto = Photo::create([
'photo_name' => $fileNameToStore,
]);
if ($addPhoto) {
return back()->with('success', 'Image Upload successfully');
}
yesterday I tried to find on internet but it's seem not result for my situation, so I try to replace $uri in route and it work,
I change from:
Route::get('images','ImagesController#index')->name('image.index');
to:
Route::get('imageproduct','ImagesController#index')->name('image.index');
but I still don't know why does error appear and how to fix it.
And I also check image link on database, it's seem not save to database, can you give me suggest about upload image . Thank You

how to save base64 image decode to public folder in laravel

I get an image with format String base64 and i want to decode that string to be an image and save it to public folder in laravel.
This is my controller:
//decode string base64 image to image
$image = base64_decode($request->input('ttd'));
//create image name
$photo_name = time().'.png';
$destinationPath = public_path('/uploads');
//save image to folder
$image->move($destinationPath, $photo_name);
$img_url = asset('/uploads'.$photo_name);
$data = new Transaction();
$data->transaction_id = $request->input('fa_transaction_id');
$data->user_id = $request->input('userid');
$data->photo_name = $photo_name;
$data->photo_url = $img_url;
$data->save();
when i'm trying echo $image, i got the decode value, and also for $photo_name i got the value too, but when the function running i got this error
Call to a member function move() on string
how to fix this error?
//Controller
use Illuminate\Support\Facades\Storage;
//Inside method
$image = $request->image; // your base64 encoded
$image = str_replace('data:image/png;base64,', '', $image);
$image = str_replace(' ', '+', $image);
$imageName = str_random(10) . '.png';
Storage::disk('local')->put($imageName, base64_decode($image));
Also, make sure that your local disk is configured like that in /config/filesystems.php
'local' => [
'driver' => 'local',
'root' => storage_path('app/public'),
]
With that, file will be saved in /storage/app/public directory.
Don't forget to write php artisan storage:link to make files from that directory available in /public directory, so users will can retrieve them.
Saving image in database not a recommanded way to store image in db, reason is speed increase of memory, The correct way is just save the link to it.
Anyway, you can save your image in base64 with these line of code.
Get the correct image from path in your server not from link in the $path.
<?php
// Base 64 transform image
$path = __DIR__ .'/myfolder/myimage.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
echo $base64;

Save and retrieve file in Laravel

I have difficulty understanding the file save and retrieval in Laravel. I managed to get the file saved into correct path
$fileNameWithExt = $request->file('Agreement_file')->getClientOriginalName();
$fileName = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
$extention =$request->file('Agreement_file')->getClientOriginalExtension();
$filenameToStore = $fileName . '_' . $lab_id. '.'.$extention;
$request->Agreement_file->storeAs('agreements', $filenameToStore );
However not I want to create an a-tag to download the file, but cannot manage to get to download the file.
{{$filenameToStore}}
The file download but I get the error "Failed- Server Problem". I do not want to use a same link as these files are confidential and should not be able to be downloaded outside the app.
Something like that?
Step 1:
Create table files id | filename | user_id.
Step 2:
Create model File
Step 3:
Add file row in table.
$fileNameWithExt = $request->file('Agreement_file')->getClientOriginalName();
$fileName = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
$extention =$request->file('Agreement_file')->getClientOriginalExtension();
$filenameToStore = $fileName . '_' . $lab_id. '.'.$extention;
$request->Agreement_file->storeAs('agreements', $filenameToStore );
File::create([
'filename' => $filenameToStore,
'user_id' => Auth::id()
]);
Step 4:
Create controller method download.
public function download(){
$filename = $request->input('filename');
$file = File::where('user_id', Auth::id())
->where('filename', $filename)
->firstOrFail();
$path = Storage::path('agreements/' . $filename);
if(Storage::exists($path)){
return Response::download($path, $filename);
}
}
Step 5:
Replace your link:
{{$filenameToStore}}
Or you can build it based on the file ID.

Laravel: Trouble with uploading files on localhost

I've trouble getting the file upload working with Laravel on my Windows 7 system. There is no issue with uploading the files but when I see the destination directory the uploaded file is not present.
After searching in Google and forums I found that there may be a problem with the 'Temp' directory.
The output of dd(sys_get_temp_dir()) is C:\Users\RAGHAV~1\AppData\Local\Temp.
However there is no directory called RAGHAV~1(I've enabled to see the hidden folders). In php.ini the upload_tmp_dir is set to C:\xampp\tmp.
Is there any conflict between these settings? Can you please help me to get the file upload working?
The code in the controller that process the uploaded files:
$validator = $this->brandValidator($request->all());
if ($validator->fails()) {
$this->throwValidationException(
$request, $validator
);
}
$image_directory = public_path() . '/Uploads/Products/';
$result = $request->file('image')->move($image_directory);
$brand_name = $request->input('brand_name');
$image = $image_directory . $request->file('image')->getClientOriginalName();
$id = Brand::create([
'brand_name' => $brand_name,
'image' => $image,
]);
You have not specified the path for the file. Simply replace this
$image_directory = public_path() . '/Uploads/Products/';
$result = $request->file('image')->move($image_directory);
with this
$file = $request->file('image');
$filename = $file->getClientOriginalName().'.' . $file->getClientOriginalExtension();
$file->move(public_path('Uploads/Products/'), $filename);

Categories