I'm using Laravel to upload an image to my folder.
$file = Input::file('largeImage');
$filePath = '/uploads/'.date("Y/m").'/'.time().'/';
$path = $filePath;
$file->move($path, $file->getClientOriginalName());
The image is successfully uploaded.
Now when I try to access it:
http://localhost:8080/uploads/2015/01/1420644761/10377625_673554946025652_6686347512849117388_n.jpg
I'm having the Symfony \ Component \ HttpKernel \ Exception \ NotFoundHttpException error.
I even tried http://localhost:8080/public/uploads/2015/01/1420644761/10377625_673554946025652_6686347512849117388_n.jpg
But the same error. What might be the problem? I checked the uploads folder and the image is there.
You need to add a call to public_path helper:
$filePath = public_path() . '/uploads/'.date("Y/m").'/'.time().'/';
Otherwise it will place it in the app root, I think.
This worked for me:
$file = Input::file('largeImage');
$filePath = '/uploads/'.date("Y/m").'/'.time().'/';
$filename = $file->getClientOriginalName();
$path = public_path().$filePath;
$file->move($path, $file->getClientOriginalName());
Ok, so it IS a Routing Issue. To solve this particular one, define a Route::get that navigates to your file.
Route::get("/download/{year}/{month}/{time}/{filename}", "Controller#downloadFile");
Then you'll need a function in that controller that handles the file download:
public function downloadFile($year, $month, $time, $filename){
$path = public_path()."/uploads/".$year."/".$month."/".$time."/".$filename".jpg";
// Should equate to: "/uploads/2015/01/142064476110377625_673554946025652_6686347512849117388_n.jpg
return Response::download($path, 'image.jpg');
}
Which in theory should work for your needs. The path may need to be modified to fit your needs but this should be the general idea. Test that out and let me know if it works.
Note
This isn't the best way to handle downloads, as you need to know the exact filename of the file you want, but it points you in the right direction.
Related
I am trying to resize images using the intervention package, but I keep on getting the error, whenever I refresh the browser page. I have already added Intervention\Image\ImageServiceProvider::class, to the providers section and, 'Image' => Intervention\Image\Facades\Image::class, to the aliases section of config/app.php file.
if($request->hasfile('image'))
{
$imagePath = $request->file('image');
$extension = $imagePath->getClientOriginalExtension();
$filename = time().'.'.$extension;
$imagePath->storeAs('public/uploads/', $filename);
}
$image = Image::make(public_path("public/uploads/{$imagePath}"))->fit(1200,1200);
$image->save();
You don't need to add "public" with the public_path() function (unless you actually have a "public" folder inside Laravel's public folder.
So your file path should probably be:
public_path("uploads/{$imagePath}")
If it still doesn't work, echo out the path to check if it's correct.
I am trying to store a file in the following path "public/uploads/images" with lumen.
Here is my code
if($request->hasFile('photo')){
$file = $request->file('photo');
$fileName = time().$counter.'.'.$request->file('photo')->getClientOriginalExtension();
$request->file('photo')->move('/uploads/images', $fileName);
return $fileName;
}
But no file is moving to the path. only the file name is returned. What is the problem and how to solve?
try to use the public_path function to upload it into public folder.
Example:
$request->file('photo')->move(public_path("/uploads"), $newfilename);
Visit https://laracasts.com/discuss/channels/laravel/image-upload-using-storage-function-to-public-folder
Im trying to save a manipulated image which i will them push to s3.
My code that works This code saves the image directly within the public folder*
public function store(Filesystem $filesystem)
{
$request = Input::all();
$validator = Validator::make($request, [
'images' => 'image'
]);
if ($validator->fails()) {
return response()->json(['upload' => 'false']);
}
$postId = $request['id'];
$files = $request['file'];
$media = [];
$watermark = Image::make(public_path('img/watermark.png'));
foreach($files as $file) {
$image = Image::make($file->getRealPath());
$image->crop(730, 547);
$image->insert($watermark, 'center');
$image->save($file->getClientOriginalName());
}
}
What i would like to achieve is to be able to save it within a folder of it's own. Firstly what is the best place to store an image for a blog post, within the storage of public folder? But anyway when i do this:
$image->save('blogpost/' . $postId . '/' . $file->getClientOriginalName());
// Or this
$image->save(storage_path('app/blogpost/' . $postId . '/' . $file->getClientOriginalName()));
I get the error:
folder within public
NotWritableException in Image.php line 138: Can't write image data to
path (blogpost/146/cars/image.jpg)
or
storage path
NotWritableException in Image.php line 138: Can't write image data to
path /code/websites/blog/storage/app/blogpost/146/image.jpg
I've tried
cd storage/app/
chmod -R 755 blogpost
And it still wont work
Thank you for reading this
Ok so here is how i solved it, I made the directory first before storing,
Storage::disk('local')->makeDirectory('blogpost/' . $postId);
Once the folder is created i then go on to store the manipulated images like so:
$image->save(storage_path('app/blogpost/' . $postId . '/' . $imageName));
And then pushing the image to S3
$filesystem->put('blogpost/' . $postId . '/' . $imageName, file_get_contents(storage_path('app/blogpost/' . $postId . '/' . $imageName)));
This worked
You can solve it by casting the Intervation/Image variable to a data stream using function stream. Then use the Storage Laravel facade to save the image.
$img = Image::make('path-to-the-image.png')->crop(...)->insert->stream('jpg', 90)
Storage::put('where_I_want_the_image_to_be_stored.jpg', $img);
Laravel 5 needs permission to write to entire Storage folder so try following,
sudo chmod 755 -R storage
if 755 dont work try 777.
Am improving #Amol Bansode answer.
You are getting this error because $postId folder does not exist in the path you specified.
You could do it like this:
//I suggest you store blog images in public folder
//I assume you have created this folder `public\blogpost`
$path = public_path("blogpost/{$postId}");
//Lets create path for post_id if it doesn't exist yet e.g `public\blogpost\23`
if(!File::exists($path)) File::makeDirectory($path, 775);
//Lets save the image
$image->save($path . '/' . $file->getClientOriginalName());
In my case I migrated a project from Windows 10 to Parrot (Debian-Linux) and I had the same problem and turned out the slashes were backward slashes and Linux interpret them differently. Unlike Windows, it doesn't really matter.
//Windows Code:
$image_resize->save(public_path('\storage\Features/' .'Name'.".".'png'));
//Linux Code (Working):
$image_resize->save(public_path('storage/Features/' .'Name'.".".'jpg'));
I know the question is related to Laravel but I came across from making it to work with WordPress. If somebody is coming from WordPress world, this code works (I was getting the same 'cannot write' error) and changing directory permission would not work as the library probably needs the relative path (the code below is valid for direct installation of Intervention through composer into any PHP application, not Laravel per se)-
require 'vendor/autoload.php';
use Intervention\Image\ImageManager;
$manager = new ImageManager(array('driver' => 'imagick'));
$image = $manager->make('PUBLIC IMAGE URL/LOCAL IMAGE PATH');
$image->crop(20, 20, 40, 40);
$image->save(__DIR__ . '/img/bar.png');
in my case:
i double check my symlinks in filesystem.php in config folder in laravel
and remove all symlink then regenerate them
php artisan storage:link
in my case my fileName is not valid format for naming in windows but it worked on linux or docker
$make_name = date('Y-m-d-H:i:s') . hexdec(uniqid()) . '.' . $img->getClientOriginalExtension();
when I remove this date('Y-m-d-H:i:s') it worked as well
I have faced the same issue but 775 permission not sort it so I changed the write permission to the folder(also sub-folders) to 777 to get over this issue.
I'm trying to manage my fileuploading but it seems I cant write to the folder public/uploads.
I have write permission so I'm not sure what it can be, does somebody see a typo?
I use the intervention/image library.
My code is:
$file = Input::file($fileName);
if ($file->isValid()) {
if ($file->getMimeType() == 'image/jpeg' || $file->getMimeType() == 'image/png') {
$path = public_path("uploads", $file->getClientOriginalName());
Image::make($file->getRealPath())->resize(180, null)->save($path);
} else {
throw new FileException;
}
}
The exception thrown is:
Intervention \ Image \ Exception \ NotWritableException
Can't write image data to path (/home/vagrant/Sites/cms/public/uploads)
I've found the typo...
I had:
$path = public_path("uploads", $file->getClientOriginalName());
Changed to:
$path = public_path("uploads/" . $file->getClientOriginalName());
Thanks for the quick answer though!
You need to check the permissions of the folder, and its parent folders. If you're on linux, it should be 644. The individual folder may have write access, but the parent might not; or it could be for the wrong user. Check the Ownership group too.
currently i am working on zf2. Right now i have to give download option to download pdf files.i have stored all the pdf files in data directory.How can i specify link to that pdf files from .phtml file?
thanks in advance.
A user will never gain direct access to your /data directory. This would be just not that good. But you can easily write yourself a download-script.php or the likes that will hand out the content of this directory to your users.
If you take a look at the first six lines of public/index.php you'll see the following:
<?php
/**
* This makes our life easier when dealing with paths. Everything is relative
* to the application root now.
*/
chdir(dirname(__DIR__));
With this in mind, you know that from PHP's side of things the access to anything inside the data directory is as simple as data/file.pdf
You'd always want to write yourself some sort of download-logger. Write yourself a controller. Have an action inside of that controller probably called something like download or anything like that. That action should have one parameter filename.
All that this action does is to check if filename exists file_exists('data/'.$filename) and if it exists, you simply deliver this file to your users. An example mix or zf2 and native php could be:
public function downloadAction()
{
$filename = str_replace('..', '', $this->params('filename'));
$file = 'data/' . $filename;
if (false === file_exists($file)) {
return $this->redirect('routename-file-does-not-exist');
}
$filetype = finfo_file($file);
header("Content-Type: {$filetype}");
header("Content-Disposition: attachment; filename=\"{$filename}\"");
readfile($file);
// Do some DB or File-Increment on filename download counter
exit();
}
This is not clean ZF2 but i'm lazy right now. It may be much much more ideal to use a proper Response Object and do the File-Handling there!
Important Update this thing was actually quite insecure, too. You need to disallow parent-folders. You wouldn't wanna have this guy do something outside of the data/download directory like
`http://domain.com/download/../config/autoload/db.local.php`
If I'm not totally mistaken, simply replacing all occurences of double-dots should be enough...
I would create a symbolic link in public directory for PDF files in data folder.
For example:
ln -s /your/project/data/pdfdir /your/project/public/pdf
and create links something like
File.pdf
Borrowing Sam's code, here's what it looks like in ZF2 syntax.
public function downloadAction()
{
$filename = str_replace('..', '', $this->params('filename'));
$file = 'data/' . $filename;
if (false === file_exists($file)) {
return $this->redirect('routename-file-does-not-exist');
}
$filetype = finfo_file($file);
$response = new \Zend\Http\Response\Stream();
$response->getHeaders()->addHeaders(array(
'Content-Type' => $filetype,
'Content-Disposition' => "attachement; filename=\"$filename\""
));
$response->setStream(fopen($wpFilePath, 'r'));
return $response;
}