Uploading files in Laravel 4
This is a super short post about uploading files with Laravel 4.
I have struggled a few minutes trying to convert this from L3 format to L4 and to save somebody time decided to post this short PHP script.
This script can work with multi file uploads that I have documented in my previous blog post on AJAX file uploads – https://maxoffsky.com/code-blog/howto-ajax-multiple-file-upload-in-laravel/ basically adapting that method to the new Laravel 4 file operations.
In your controller where you POSTing your file upload, insert the following code:
$file = Input::file('file');
$destinationPath = 'uploads';
// If the uploads fail due to file system, you can try doing public_path().'/uploads'
$filename = str_random(12);
//$filename = $file->getClientOriginalName();
//$extension =$file->getClientOriginalExtension();
$upload_success = Input::file('file')->move($destinationPath, $filename);
if( $upload_success ) {
return Response::json('success', 200);
} else {
return Response::json('error', 400);
}
This will give your file a random filename and save it in the uploads folder.
Enjoy!
UPDATE:
I wrote a lengthy chapter of a book about AJAX file uploads and included a server-side example built with Laravel. Check it out here: http://leanpub.com/frontend
Uploading files in Laravel 4 http://t.co/y1gbRJh7ZP
RT @msurguy: Uploading files in Laravel 4 http://t.co/y1gbRJh7ZP
RT @msurguy: Uploading files in Laravel 4 http://t.co/y1gbRJh7ZP
RT @msurguy: Uploading files in Laravel 4 http://t.co/y1gbRJh7ZP
RT @msurguy: Uploading files in Laravel 4 http://t.co/y1gbRJh7ZP
Thanks for sharing!
Hi there Max, I was looking for this 🙂
What I actually want is to extend on it… Here’s the business logic of my project:
1. When a user registers, a folder with their name is created on the server.
2. When they upload files, the files will then be uploaded to their folder.
Now my problem is: how do I use The SESSION variable to create the folder and upload the file? I’ve been in an adventure of trial and error lol.
This sure shed some light into what I wanna do. But any help you can give is welcome. Thanks again, I always find your posts useful.
Regards
Osvaldo Manuel
Why do you need to use the session variable?
You can use the user’s folder (preferably you store the name of the folder as a random text string 10-16 characters long in the DB, for example in column named foldername) and upload the files into it like this :
$file = Input::file('file');
$destinationPath = 'uploads/'.Auth::user()->foldername;
$filename = $file->getClientOriginalName();
$upload_success = Input::file('file')->move($destinationPath, $filename);
if( $upload_success ) {
return Response::json('success', 200);
} else {
return Response::json('error', 400);
}
That’s pretty much it =)
Of course you might want to make sure that the files don’t overwrite each other if they have the same file name. To do that you will need to add more things, you will need to give a random name to the file (str_random(12) but preserving extension with $extension =$file->getClientOriginalExtension();) when you are saving the file and also save file’s real name in the DB under column “alias”. Then you can do some magical things with that and your files will never overlap and won’t be rewritten.
Hope this helps.
Let me know if you have more questions.
in my laravel app i’m trying to upload an image, this works, I save the image in /uploads/ but when I try to show it I can’t access to the folder, how can I do?
what do you get? what errors?
good afternoon, the problem is I do not know how to tell the view what is file path, my upload folder is in the root
How to show url which is image uploaded ?
Thanks
This is very good tutorial. I would like to do the same but mine will be like user register to my site then all the registered user will access the download section where i will be having a list of file for download eg pdf, docx and even zip files. So how can implement the download part for only users using laravel 4. An example will be really nice or advice.
You can check if the user has permissions to download the file (this will be up to you how you want to check that, probably in the controller or even in the model) and then you can use the following StackOverflow answer to initiate the download of large size files:
http://stackoverflow.com/questions/15942497/why-dont-large-files-download-easily-in-laravel
Hi Mark.
Thanks for this nice tutorial. By any chance do you have this project in github or have it somewhere we can get the source code for the entire project.
I’m sorry I don’t have it up on Github yet but I am going to put a lot of my projects on Github soon, please subscribe to my blog so you know when it will be posted!
Sorry for digging out old post but I have problem with laravel 4 and dropzone. If i choose multiple file (for example 10 images) laravel uploads it in weird way – for example creates 10 files on server but it looks like only 2 images were uploaded couple of times.. Code is same as yours, i only resize uploaded and moved images.
thank’s for sharing mark, awesome !
it shows success. but the file is not actually uploaded in that folder and no error showing
Thanks for the useful post. May I ask why random folder instead of a random file name? Preserving the original name can be achieved by storing the value in a DB. Persistence is an inevitable requirement considering that even the random folder name needs to be remembered. I feel we are creating additional load on the filesystem with the random folder approach.
Good notice, Aditya! I think the project I was doing at the time required separate folders for some of the uploads but overall of course it is better to have as few folders as possible and random filenames for files inside the folders. I’ll update the code to reflect that.
Thanks a lot! One question, if I wanted to use a csrf token, for security, how would your approach be ?
You would have to attach it as an additional form field. Also research a bit about CSRF with AJAX in Laravel.
Nice tut bro ! And what about pushing image name to database. is that possible ? I m newbie for laravel
You would just save the filename to the database, not the whole file. I will be releasing a chapter of a book about this soon.
hi Maks, thanks for sharing this. i have a problem while using this as: TokenMismatchException, can you pls help me.?
That has to deal with CSRF token. You might want to disable the CSRF token filter for the route that handles the file upload and it should work fine.
Hi, How would you save the path of the image to the db? Also, how would you handle if you upload multiple files, then save each one to the db?
Hello! I just store the path relative to the public folder and use “url(‘uploads/myfile.jpg’)” format to get the full URL of the file. The multiple file upload is just done by saving the path to each file into a separate row in the DB.
This way it seems like you’re referring to one file. What if they are multiple files?
Parallel uploads is not something you would ever want to do on a website unless you have your own private server with a huge(or unlimited) amount of RAM. The best and most optimal way is to do sequential file uploads and most file uploading plugins allow you to do that.
Thanks. Also, you should add public_path() to your $destinationPath like so public_path() . ‘/uploads’ . That gave me issue for a while till I figured it out
thanks! Will add that to the post as an “FYI”
This work whit ajax???
Yes it does.
Works like a charm. Thank you!
sorry to say this but when I do the upload, only a few of the many uploads I make successed in uploading and the problem is that I don’t any errors to pinpoint if there is any problem !!
This means something is wrong with the server and how it handles PHP uploads…
WORKS LIKE A CHARM!
Great work!
Thanks! Enjoy!
cool. got basics from here and also found nice tutorial here http://tutsnare.com/upload-files-in-laravel/ and both makes my work easy. well done.
An complete example of laravel file upload is given here . you can read about laravel file upload function reference from here http://www.tutsway.com/laravelfileupload.php.
for Laravel 5 ?
Valuable comments . Talking of which , if one is wanting to merge two PDF files , my business partner encountered presentation here
https://goo.gl/6542R3
this is a waste of time- how about posting current information
at the point when the information you’ve posted is obsolete you should have the sense to remove it