valentin vannay

valentincognito

[Laravel 5] Multiple files upload

2016-01-07

Laravel 5 offers a few out of the box helpers to perform files upload and download but as usual I think the official laravel documentation lacks a bit of information for intermediate developers like myself. So let me guide you more in detail in the process of creating a form to upload content to your server easily.

The Form

The first thing you need is an html form to allow the user to browse and select files to upload. I personnaly don't use the HTML form blade templating anymore since it's not shipped with laravel by default. So here is our simple form with a hidden input for the CSRF Token, a file input and a submit button. Note that the traditional file input requires 2 additional things in order to allow multiple file treatments. 1. An array for the name e.g: name="myarray[]" 2. The attribute: multiple This attribute will simply allow multiple selection by pressing the shift key and clicking on different files in your explorer.
// Simple HTML form for files upload
<form role="form" method="POST" action="{{ url('/upload') }}" enctype="multipart/form-data">
  <input type="hidden" name="_token" value="{{ csrf_token() }}">
  <input type="file" name="attachments[]" multiple/>
  <input name="save" type="submit" value="Save">
</form>

The Route

Route::post('upload', 'UploadController@storeFiles');

The Controller

/**
 *  Store Files
 *
 * @return Redirect
 */
public function storeFiles()
{
  // Request the file input named 'attachments'
  $files = Request::file('attachments');

  //If the array is not empty
  if ($files[0] != '') {
    foreach($files as $file) {
      // Set the destination path
      $destinationPath = 'uploads';
      // Get the orginal filname or create the filename of your choice
      $filename = $file->getClientOriginalName();
      // Copy the file in our upload folder
      $file->move($destinationPath, $filename);
    }
  }
  // Retrun a redirection or a view 
  return redirect('/');
}
The controller is pretty self-explanatory you get your input, check if the array of file is not empty, set a new filename or get the orginal one set the destination and save the file. The destination base folder is your public folder in your application. So in this example the stored files can be found in /public/uploads. Also in the above controller I used the laravel helper:
$file->getClientOriginalName();
Here are a few more you can conveniently use:
$files->getRealPath();
$files->getClientOriginalExtension();
$files->getSize();
$files->getMimeType();
Of course at this stage the process is absolutely not secure. If this form is for clients you must check and regulate the size / type of the files !! But this will not be covered here. But for further reading you can read the laravel validation process or this article that explains pretty well of to secure your files upload.