Upload image and extract filename instead of file path - laravel-5.6

I am using following code to upload thumbnail in "storage/app/public/websites"
$path = $request->file('thumbnail')->store('public/websites');
It is working fine and upload images to "websites" directory but problem is it returns the actual path e.g. websites/r63mAKN1kil3BIwvwwRevOv93MgWQFme39BwH8ZV.jpeg
i only want to save image name e.g. r63mAKN1kil3BIwvwwRevOv93MgWQFme39BwH8ZV.jpeg in database table.
By default Laravel generates Unique ID for image name. Is there way to return only filename instead of path ?

This is the hash name, so, first I think you need to separate your steps.
$file = $request->file('thumbnail');
$path = $file->store('public/websites');
when you need to add file name you can use $file->hashName();

You can use the basename function
http://php.net/manual/en/function.basename.php
$filename = basename($path);

This is what you need
$extension = $request->image->getClientOriginalExtension();
$image_name = str_replace(' ', '', trim($request->model) . time() . "." . $extension);
and to move the image to your desired folder use:
$image_path = $request->image->move(public_path('images'), $image_name);

$info = pathinfo( $url );
$contents = ( new \GuzzleHttp\Client() )->get( $url, [ 'verify' => true ] )->getBody()->getContents();
$file = str_finish(sys_get_temp_dir(), '/') . $info[ 'basename' ];
\File::put( $file, $contents );
$ext = ( new UploadedFile( $file, $info[ 'basename' ] ) )->guessExtension();

Related

How to Save File in storage folder with Original name?

I want to store an uploaded file with its original client name in the storage folder. What do I need to add or change in my code?Any help or recommendation will be greatly appreciated
Here my Controller
public function store(Request $request) {
$path = "dev/table/".$input['id']."";
$originalName = $request->file->getClientOriginalName();
$file = $request->file;
Storage::disk('local')->put($path . '/' . $originalName, $request->file);
}
Edit: I know how to get the originalClientName. the problem is storing the file in the folder using the original name, not the hash name. It doesn't store in the file in the original it makes a new folder instead here is the output "dev/table/101/Capture1.PNG/xtZ9iFoJMoLrLaPDDPvc4DMJEXkRL3R4qWOionMC.png" what I trying to get is "dev/table/101/Capture1.PNG"
I have tried to use StoreAs Or putFileAs but the method is undefined
I managed to figure out how to store it with a custom name, for those who want to know how to do it here is the code
$id = $input['id'];
$originalName = $request->file->getClientOriginalName();
$path = "dev/table/$id/".$originalName;
Storage::disk('local')->put($path, file_get_contents($request->file));
public function store(Request $request) {
$originalName = $request->file->getClientOriginalName();
$extension = $request->file->getClientOriginalExtension();
$path = "dev/table/" . $input['id'] . "/" . $originalName . "." . $extension;
$file = $request->file;
Storage::disk('local')->put($path, $file);
}
To get the original file name you can use this in your ControllerClass:
$file = $request->file->getClientOriginalName();
To get additional the extension you can use this Laravel Request Method:
$ext = $request->file->getClientOriginalExtension();
Then you can save with:
$fileName = $file.'.'.$ext;
$request->file->storeAs($path, $fileName);
// or
Storage::disk('local')->put($path . '/' . $fileName , $request->file);
You can save files using storage with the default name using putFileAs function instead of put which allow take third param as a file name
$path = "dev/table/101/";
$originalName = request()->file->getClientOriginalName();
$image = request()->file;
Storage::disk('local')->putFileAs($path, $image, $originalName);
Update
You can do something like this with put,
Storage::disk('local')->put($path.$originalName, file_get_contents($image));
I tried to manage like this;
$insurance = $request->file('insurance_papers');
$insuranceExtention = $insurance->getClientOriginalExtension();
$path = "public/files/" . $carrier->id . "/insurance_papers." . $insuranceExtention;
Storage::disk('local')->put($path, file_get_contents($insurance));
You can try this, this is work for me
if ($request->hasFile('attachment')) {
$image = $request->file('attachment');
$imageName = time() . '.' . $image->getClientOriginalExtension();
$path = "foldername/".$imageName;
Storage::disk('public')->put($path, file_get_contents($image));
}

Resize image and store it to s3

Default image upload process in my app like this.
Get image from request and store it to s3 and a local variable.
$path = $request->file("image")->store("images", "s3");
After this I make it public.
Storage::disk("s3")->setVisibility($path, 'public');
And store to DB like this.
$variable = ModelName::create([
"image" => basename($path),
"image_url" => Storage::disk("s3")->url($path),
But how to resize the image before store it to s3?
I try to write like this
$extension = $request->file('image')->getClientOriginalExtension();
$normal = Image::make($request->file('image'))->resize(160, 160)->encode($extension);
$filename = md5(time()).'_'.$request->file('image')->getClientOriginalName();
$img = Storage::disk('s3')->put('/images/'.$filename, (string)$normal, 'public');
And then
"image" => basename($filename ),
"image_url" => Storage::disk("s3")->url($img),
This works except one thing. I can't get URL (to store DB) for uploaded image.
How to get correct public url for uploaded image?
Note:I use Intervention Image package
Storage::put() would only return the path if it's an instance of File or UploadedFile (source). In this case $normal isn't, so put() would return a boolean instead. Also, using getClientOriginalExtension() probably isn't a good idea since it's not considered a safe value (source).
So here's a bit improved version:
$filename = $request->file('file')->hashname();
$image = Image::make($request->file('file'))->resize(160, 160);
Storage::disk('s3')->put('/images/'.$filename, $image->stream(), 'public');
$url = Storage::disk('s3')->url('/images/'.$filename);
You can now save $url and $filename into your db.
You can try my code snippet.
$file = $request->file('image');
$fileName = md5(time()).'.'.$file->getClientOriginalExtension();
/** #var Intervention $image */
$image = Image::make($file);
if ($image->width() > ($maxWidth ?? 500)) {
$image = $image->resize(500, null, function ($constraint) {$constraint->aspectRatio();});
}
$image = $image->stream();
try {
/** #var Storage $path */
Storage::disk('s3')->put(
$dir . DIRECTORY_SEPARATOR . $fileName, $image->__toString()
);
} catch (\Exception $exception) {
Log::debug($exception->getMessage());
}

Laravel 5.4 Error: NotReadableException: Image source not readable

I'm trying to create multiple copies of profile pic in different sizes when a profile is created. But I am constantly getting this error:
" NotReadableException: Image source not readable"
Can somebody point me what I'm missing in my below code:
public function updateprofile(UserProfileRequest $request){
$user_id = Auth::User()->id;
$profile = UserProfile::where('user_id','=',$user_id)->first();
$profile->fullname = $request->fullname;
if ($request->hasFile('img')) {
if($request->file('img')->isValid()) {
$types = array('_original.', '_32.', '_64.', '_128.');
$sizes = array( '32', '64', '128');
$targetPath = 'public/uploads/'.$user_id;
try {
$file = $request->file('img');
$ext = $file->getClientOriginalExtension();
$fName = time();
$original = $fName . array_shift($types) . $ext;
Storage::putFileAs($targetPath, $file, $original);
foreach ($types as $key => $type) {
$newName = $fName . $type . $ext;
Storage::copy($targetPath . $original, $targetPath . $newName);
$newImg = Image::make($targetPath . $newName);
$newImg->resize($sizes[$key], null, function($constraint){
$constraint->aspectRatio();
});
$newImg->save($targetPath . $newName);
}
$profile->img = 'public/uploads/'.$user_id;
} catch (Illuminate\Filesystem\FileNotFoundException $e) {
}
}
}
$profile->save();}
I had the same issue i ran this command and it worked
php artisan storage:link
This command creates a storage directory under the public folder.
Also use public path function to get the public path
$targetPath = public_path('storage/uploads/'. $user_id);
The 'storage' used inside the laravel public_path() function is used to get the storage main folder.
If I'm not mistaken, the path which is provided should be the absolute filepath on your server. For example instead of:
$targetPath = 'public/uploads/'.$user_id;
Use (your actual path will vary depending on your configuration)
$targetPath = '/var/www/sitename/public/uploads/'.$user_id;
Laravel also contains a helper function called public_path() which can be used to obtain the "fully qualified path to the public directory". This would allow you to use something such as:
$targetPath = public_path('uploads/'. $user_id);
Also, on this line, do not forget to place a slash before the new filename:
$newImg = Image::make($targetPath . '/' . $newName);
I would also confirm that the user executing the script (if apache or nginx usually www-data unless altered) has write permissions to your public/uploads/ directory
Finally, I got it working. I made following changes to my code:
Use the full OS path as suggested by commanderZiltoid for the destination path.
Don't use Storage::putFileAs method to save the file. So, remove this line: Storage::putFileAs($targetPath, $file, $original);
Don't use Storage::copy() to copy the file, so, remove this line:
Storage::copy($targetPath . $original, $targetPath . $newName);
For points 2 and 3, use Image::make($file->getRealPath()); This will create the file and remember the path where the file was created. Image->resize method will use this path later.
In the end, save the relative path in the database, as here: $profile->img = 'storage/uploads/'.$user_id.'/img/profile/'.$fName. Since we'll use {{ asset($profile->img) }}, it's necessary to save only the relative path and not the absolute OS path.
if($request->hasFile('img')) {
if($request->file('img')->isValid()) {
$types = array('_original.', '_32.', '_64.', '_128.');
$sizes = array( array('32','32'), array('64','64'), array('128','128'));
$targetPath = '/Users/apple/Documents/_chayyo/chayyo/storage/app/public/uploads/'.$user_id.'/img/profile/';
try {
$file = $request->file('img');
$ext = $file->getClientOriginalExtension();
$fName = time();
$o_name = $fName . array_shift($types) . $ext;
$original = Image::make($file->getRealPath());
$original->save($targetPath . $o_name);
foreach ($types as $key => $type) {
$newName = $fName . $type . $ext;
$newImg = Image::make($file->getRealPath());
$newImg->resize($sizes[$key][0], $sizes[$key][1]);
$newImg->save($targetPath . $newName);
}
$profile->img = 'storage/uploads/'.$user_id.'/img/profile/'.$fName;
}
catch (Illuminate\Filesystem\FileNotFoundException $e) {
}
}
}

Laravel 5.2: how create image file from json

In my controller i receive from form data like this:
"output":{"width":500,"height":500,"image":"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQFAH/9k=..."},"actions":{"crop":{"x":97,"y":0,"height":500,"width":500},"size":null}}[
Can I create image file from this data?
upd 1.
Decode the json - ok, pull out the image data - ok, decode the base64 - ok, but when I try write to disk then I got error: NotReadableException in Decoder.php line 96: Unable to init from given binary data.
$file = Request::input('photo');
$imagedata=json_decode($file);
$file=$imagedata->output->image;
$image = base64_decode($file);
$png_url = "user-".time().".png";
$path = "/public/".$png_url;
Image::make($image)->save($path);
upd 2.
Solved with file_put_contents function.
here is how you can save image from a json data:
$data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
. 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
. 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
. '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
$data = base64_decode($data);
$im = imagecreatefromstring($data);
if ($im !== false) {
echo imagejpeg($im , base_path() . DIRECTORY_SEPARATOR . "sth.jpeg") ;
}
else {
echo 'An error occurred.';
}
This is working:
$file = Request::input('photo');
$imagedata=json_decode($file);
$file=$imagedata->output->image;
$png_url = "user-".time().".png";
$path = "uploads/".$png_url;
$image = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $file));
file_put_contents($path, $image);

Laravel 4 upload 1 image and save as multiple (3)

I'm trying to make an image upload script with laravel 4. (using Resource Controller) and i'm using the package Intervention Image.
And what i want is: when uploading an image to save it as 3 different images (different sizes).
for example:
1-foo-original.jpg
1-foo-thumbnail.jpg
1-foo-resized.jpg
This is what i got so far.. it's not working or anything, but this was as far as i could get with it.
if(Input::hasFile('image')) {
$file = Input::file('image');
$fileName = $file->getClientOriginalName();
$fileExtension = $file->getClientOriginalExtension();
$type = ????;
$newFileName = '1' . '-' . $fileName . '-' . $type . $fileExtension;
$img = Image::make('public/assets/'.$newFileName)->resize(300, null, true);
$img->save();
}
Hopefully someone can help me out, thanks!
You may try this:
$types = array('-original.', '-thumbnail.', '-resized.');
// Width and height for thumb and resized
$sizes = array( array('60', '60'), array('200', '200') );
$targetPath = 'images/';
$file = Input::file('file')[0];
$fname = $file->getClientOriginalName();
$ext = $file->getClientOriginalExtension();
$nameWithOutExt = str_replace('.' . $ext, '', $fname);
$original = $nameWithOutExt . array_shift($types) . $ext;
$file->move($targetPath, $original); // Move the original one first
foreach ($types as $key => $type) {
// Copy and move (thumb, resized)
$newName = $nameWithOutExt . $type . $ext;
File::copy($targetPath . $original, $targetPath . $newName);
Image::make($targetPath . $newName)
->resize($sizes[$key][0], $sizes[$key][1])
->save($targetPath . $newName);
}
Try this
$file = Input::file('userfile');
$fileName = Str::random(4).'.'.$file->getClientOriginalExtension();
$destinationPath = 'your upload image folder';
// upload new image
Image::make($file->getRealPath())
// original
->save($destinationPath.'1-foo-original'.$fileName)
// thumbnail
->grab('100', '100')
->save($destinationPath.'1-foo-thumbnail'.$fileName)
// resize
->resize('280', '255', true) // set true if you want proportional image resize
->save($destinationPath.'1-foo-resize-'.$fileName)
->destroy();

Resources