10 packages to deal with file uploads in laravel

Deven Rathore 16 min read
10 packages to deal with file uploads in laravel

Here is the list of 10 laravel packages that will help you to easily deal with laravel file uploads these all packages are tested with laravel 5.1 give them a try i am sure you will like them

#1- laravel-plupload

Laravel 5/Plupload – Handle large file uploads

this pacakge allows you to to upload or handle large file uploads in laravel ! give it a try i am sure you will like it

License

MIT

Links

GitHubPackagist

# 2 laravel-filemanager

This package is functional, but is under active development.

equirements

  1. This package only supports Laravel 5.x
  2. Requires "intervention/image": "2.*"
  3. Requires PHP 5.5 or later

Installation

  1. Installation is done through composer and packagist. From within your project root directory, execute the following command:composer require tsawler/laravel-filemanager
  2. Next run composer update to install the package from packagist:composer update
  3. Add the ServiceProvider to the providers array in config/app.php:'TsawlerLaravelfilemanagerLaravelFilemanagerServiceProvider',
  4. Publish the package’s config file:php artisan vendor:publish --tag=lfm_config
  5. Publish the package’s public folder assets:php artisan vendor:publish --tag=lfm_public
  6. If you want to customize the look & feel, then publish the package’s views:php artisan vendor:publish --tag=lfm_views
  7. By default, the package will use its own routes. If you don’t want to use those routes, change this entry in config/lfm.php to false:
        'use_package_routes' => true,

    You will, of course, have to set up your own routes.

  8. If you don’t want to use the default image/file directory or url, update the appropriate lines in config/lfm.php:
        'images_dir'         => 'public/vendor/laravel-filemanager/images/',
        'images_url'         => '/vendor/laravel-filemanager/images/',
        'files_dir'          => 'public/vendor/laravel-filemanager/files/',
        'files_url'          => '/vendor/laravel-filemanager/files/',
  9. Ensure that the files & images directories are writable by your web serber
  10. In the view where you are using a CKEditor instance, use the file uploader by initializing the CKEditor instance as follows:
        <script>
            CKEDITOR.replace( 'editor', {
                filebrowserImageBrowseUrl: '/laravel-filemanager?type=Images',
                filebrowserBrowseUrl: '/laravel-filemanager?type=Files'
            });
        </script>

    Here, “editor” is the id of the textarea you are transforming to a CKEditor instance. Note that if you are using a custom route you will have to change /laravel-filemanager?type=Images to correspond to whatever route you have chosen. Be sure to include the ?type=Images parameter.

Security

It is important to note that if you use your own routes you must protect your routes to Laravel-Filemanager in order to prevent unauthorized uploads to your server. Fortunately, Laravel makes this very easy.

If, for example, you want to ensure that only logged in users have the ability to access the Laravel-Filemanager, simply wrap the routes in a group, perhaps like this:

Route::group(

This approach ensures that only authenticated users have access to the Laravel-Filemanager. If you are using Middleware or some other approach to enforce security, modify as needed.

 

License

MIT

Links

GitHubPackagist

 

 

 

#3 laravel-magic-rest

Universal REST contoller for CRUD operations with dynamic routes and support for file uploads.

Universal REST contoller for CRUD operations with dynamic routes and support for file uploads.

Each route returns JSON. Example of routes wich will be available automatically:

GET     /rest/rest/book    get list of AppBooks models
POST    /rest/rest/book    

Installation

Simply do:

composer 

and then add service provider to config/app.php

    

If you need change default route prefix /rest to something else then you must execute php artisan vendor:publish and edit config/magic-rest.php

 

 

License

MIT

Links

HomepageBitBucketPackagist

 

 

#4 Upchuck

Upchuck is a simple, automatic handler of file uploads for Laravel’s Eloquent models using using Flysystem. It does not attempt to do anything besides let the developer treat file uploads like regular input fields. It does this by listening to Eloquent saving events, checking the request input for files with names that you have whitelisted, pushing those files to “disk” of your choosing, and then storing the publically accessible URL in the model attribute for that input.

Installation

  1. Add to your project: composer require bkwld/upchuck:~1.0
  2. Add Upchuck as a provider in your app/config/app.php’s provider list: 'BkwldUpchuckServiceProvider',
  3. Publish the config: php artisan config:publish bkwld/upchuck

Usage

Edit the disk config setting to supply configuration information for where uploads should be moved. We are using Graham Campbell’s Flysystem integration for Laravel to instantiate Flysystem instances, so the configruation of the disk matches his configuration options for connections. As the comments in the config file mention, I recommend turning on caching if you are using any disk other than local. For both caching and other disk drivers, you will need to include other packages.

Then, to enable upload support for your models, use the BkwldUpchuckSupportsUploads trait on your model and itemize each attribute that should support uploads via the $upload_attributes property. For example:

class Person extends Eloquent {

    // Use the trait
    use BkwldUpchuckSupportsUploads;

    // Define the uploadable attributes
    protected $upload_attributes = [

        // Both the file input field and the model attribute are named "image"
        'image',

        // The input file field is named "portrait" but the model attribute is
        // named "headshot"
        'portrait' => 'headshot',
    ];

    // Since the upload handling happens via model events, it acts like a mass
    // assignment.  As such, Upchuck sets attributes via `fill()` so you can
    // control the setting.
    protected $fillable = ['image', 'headshot'];
}

Resizing images

If your app supports uploading files you are probably also dealing with needing to resize uploaded images. We (BKWLD) use our Croppa package to resize images using specially formatted URLs. If you are looking for an model-upload package that also resizes images, you might want to check out Stapler.

Deleting images

If you update a model attribute to a false-y value, Upchuck will delete the old referenced file. Thus, if your app allows users to delete files, consider using markup like:

<input type="file" name="image">
Delete file <input type="checkbox" name="image" value="">

Array-ish inputs

If your field is like this:

<input type="file" name="types[marquee][image]">

Setup your $upload_attributes like:

protected $upload_attributes = [
    'types.stats.image' => 'image',
];


License

MIT

Links

GitHubPackagist


#5 laravel-uploader

Easy file upload and validations for Laravel.

Installation

 

$ composer require "escapework/laravel-uploader:0.1.*"

License

MIT

Links

GitHubPackagist


#6 laravel-fileupload

File uploading library capable of handling large/chunked/multiple file uploads

FileUpload

PHP FileUpload library that supports chunked uploads. Adopted from the procedural script included with jQuery-File-Upload, designed to work with that JavaScript plugin, with normal forms, and to be embeddable into any application/architecture.

Installing

This package is available via Composer:

{
  "require": {
    "gargron/fileupload": "~1.0.*"
  }
}

Status

The unit test suite covers simple uploads, and the library “works on my machine,” as it were. You are welcome to contribute.

You can grep the source code for “TODO” to find things you could help finishing.

Usage

// Simple validation (max file size 2MB and only two allowed mime types)
$validator = new FileUploadValidatorSimple(1024 * 1024 * 2, ['image/png', 'image/jpg']);

// Simple path resolver, where uploads will be put
$pathresolver = new FileUploadPathResolverSimple('/my/uploads/dir');

// The machine's filesystem
$filesystem = new FileUploadFileSystemSimple();

// FileUploader itself
$fileupload = new FileUploadFileUpload($_FILES['files'], $_SERVER);

// Adding it all together. Note that you can use multiple validators or none at all
$fileupload->setPathResolver($pathresolver);
$fileupload->setFileSystem($filesystem);
$fileupload->addValidator($validator);

// Doing the deed
list($files, $headers) = $fileupload->processAll();

// Outputting it, for example like this
foreach($headers as $header => $value) {
  header($header . ': ' . $value);
}

echo json_encode(array('files' => $files));

Validator

If you want you can use the common human readable format for filesizes like “1M”, “1G”, just pass the String as the first Argument.

$validator = new FileUploadValidatorSimple("10M", ['image/png', 'image/jpg']);

Here is a listing of the possible values (B => B; KB => K; MB => M; GB => G). These values are Binary convention so basing on 1024.

FileNameGenerator

With the FileNameGenerator you have the possibility to change under witch Filename we uploaded files will be saved.

$fileupload = new FileUploadFileUpload($_FILES['files'], $_SERVER);
$filenamegenerator = new FileUploadFileNameGeneratorSimple();
$fileupload->setFileNameGenerator($filenamegenerator);

We have placed some example generators like md5 who saves the file under the md5 hash of the filename or the random generator witch uses an random string. The default (the simple generator to be more precise) will save the file by its origin name.

Callbacks

Currently implemented events:

  • completed
$fileupload->addCallback('completed', function(FileUploadFile $file) {
  // Whoosh!
});

Extending

The reason why the path resolver, the validators and the file system are abstracted, is so you can write your own, fitting your own needs (and also, for unit testing). The library is shipped with a bunch of “simple” implementations which fit the basic needs. You could write a file system implementation that works with Amazon S3, for example.

 

#7 upload

File upload library for laravel

License

MIT

Links

HomepageGitHubPackagist

 

 

#8 laravel-file-uploader

Web Form File Uploader for Laravel

Laravel File Uploader is a web form upload manager for Laravel 5.1. This package provides additional files for the craigh411/FileUploader package for use within the Laravel framework. FileUploader uses the same symfony/HttpFoundation package used by laravel for file uploads, so is easily integrated, but adds some additional functionality to make file uploads a breeze.

Features

  • Allow and block specific mime types.
  • Adjust maximum file size.
  • Choose to automatically create upload directories.
  • Allow file overwriting
  • Automatically create sanitised file names.
  • Create unique file names

Installation

Install via Composer with:

composer require craigh/laravel-file-uploader

or you can add:

"craigh/laravel-file-uploader": "~1.0"

to the require section of your composer.json file and run composer update from the command line.

You should also register the service provider by adding the following to providers in config/app.php:

HumpsLaravelFileUploaderFileUploaderServiceProvider::class

Creating an Alias (Optional)

While not required, if you want to use the facade you need to add the following to aliases in config/app.php:

'Upload' => HumpsLaravelFileUploaderFacadesUploaderFacade::class

You will then be able to use the Upload alias to use the facade.

Basic Usage

Beacuse LaravelFileUploader uses the symfony/HttpFoundation you can pass $request->file('input_name') directly into the file method.

If you’ve added the alias for the facade, then you can use:

Upload::file($request->file('file'))->move();

You will need to use Upload to get this to work if you are working inside a namespaced class.

If you are not using the facade you can type hint LaravelFileUploader in your classes methods or constructor or if you prefer you can simply call:

$upload = App::make('upload');

Changing Settings Directly

If you want to change the default settings then you can simply chain them together like so (See Methods at the bottom for the full settings list):

Upload::file($request->file('file')))
->createDirs(true)
->maxFileSize(5,'MB')
->allowedMimeTypes(['image/jpeg', 'image/png', 'image/gif'])
->move();

Note: The move() method returns the upload path, so must be chained to the end.

Configuring Using Inheritance

For a clean configuration you can extend the LaravelFileUploader class which gives you access to the following protected variables:

protected $uploadDir; // Upload directory
protected $allowedMimeTypes = []; // Only allow these file to be uploaded
protected $blockedMimeTypes = []; // Don't allow these files to be uploaded
protected $maxFileSize = 1000000; // In bytes
protected $makeFilenameUnique = false; // Make the filename unique if two files have the same name
protected $overwrite = false; // Allow overwriting of files with the same name
protected $createDirs = false; // Allow the automatic creation of any upload directories

e.g. For an ImageUploader you may do the following:

use HumpsLaravelFileUploaderLaravelFileUploader;

class ImageUploader extends LaravelFileUploader{

   protected $uploadDir = 'images/';
   protected $maxFileSize = 5+6e; // 5 MB
   protected $createDirs = true;
   protected $makeFilenameUnique = true;

   protected $allowedMimeTypes = [
    'image/jpeg',
    'image/png',
    'image/gif'
   ];

}

This can now be used in your classes which will automatically use those values as defaults:

/**
 * Example using dependency injection
 **/
private $upload;

public __constructor(ImageUploader $upload){
    $this->upload = $upload;
}

public function store(Request $request){
    $this->upload->file($request->file('file'))->move();
}

HumpsFileUploaderUploader Interface

You can also bind to the HumpsFileUploaderUploader interface. To do this place the following inside the register() method of your AppServiceProvider:

App::bind('HumpsFileUploaderContractsUploader','HumpsLaravelFileUploaderLaravelFileUploader');;

You can then type hint the interface instead of the concrete class:

use HumpsFileUploaderUploader;

private $upload;

public __constructor(Uploader $upload){
    $this->upload = $upload;
}

Now you can swap out your own implementations simply by changing the bound class e.g.:

App::bind('HumpsFileUploaderContractsUploader','YourNamespaceYourFileUploader');;

Methods

uploadDir(string)

Sets the upload directory. It will also append any required ‘/’ if it is not set, so both ‘path/to/dir’ and ‘path/to/dir/’ will work.

$upload->uploadDir('path/to/dir');

Note: The public folder will be the base directory for your uploads, so if you set your upload path to ‘images’ ($upload->uploadDir('images');) this will upload to the public/images folder.

overwrite(boolean)

Set to true to allow overwriting of files with the same name (default: false)

$upload->overwrite(true);

allowedMimeTypes(array)

Pass in an array of allowed mime types, everything else will be blocked. When empty all file types will be allowedunless explicitly blocked.

$upload->allowedMimeTypes(['image/jpeg, 'image/png', 'image/gif']);

blockedMimeTypes(array)

You can also block file types if you prefer. Pass in an array of mime types you want to block

$upload->blockedMimeTypes(['application/x-msdownload']);

maxFileSize($size, $unit)

The maximum file size you want to allow, expects size to be a number and unit to be either:

  • B – Byte
  • KB – Kilobyte
  • MB – Megabyte

$upload->maxFileSize(5, 'MB');

You can also use the words BYTE, BYTES, KILOBYTE, KILOBYTES, MEGABYTE or MEGABYTES if you prefer:

$upload->maxFileSize(1, 'MEGABYTE');

createDirs(bool)

If set to true this will recursively create any specified directories if they do not exist (default: false)

$upload->createDirs(true);

makeFilenameUnique(bool)

If set to true this will make the filename unique by appending a _{number} to the end.

$upload->makeFilenameUnique(true);

filename(string)

By default the filename will be a sanitised version of the uploaded filename. Use this method if you want to set your own filename.

$upload->filename('myFile.txt');

Note: When using this method the filename will not be sanatised, if you want to sanatise the filename you can use the sanitizeFilename() method.

sanitizeFilename()

Sanitises the given filename by removing any non alpha numeric characters and replacing any spaces with an underscore. You will only need to call this if you want to set your own filenames using the filename() method, otherwise this method is called automatically. You should also be aware that this call will need to be made after you set your filename:

$upload->filename
move()

Moves the file to it’s destination and returns the upload path.

$uploadPath = $upload->move();

You can also use upload() which is an alias of move() if you feel the wording is more appropriate:

$uploadPath = $upload->upload();

That’s it!

License

mit

Links

GitHubPackagist

 

#9 laravel5-file-uploader

laravel5 file uploader

License

MIT

Links

GitHubPackagist

#10 upchuck

Upchuck is a simple, automatic handler of file uploads for Laravel’s Eloquent models using using Flysystem. It does not attempt to do anything besides let the developer treat file uploads like regular input fields. It does this by listening to Eloquent saving events, checking the request input for files with names that you have whitelisted, pushing those files to “disk” of your choosing, and then storing the publically accessible URL in the model attribute for that input.

Installation

  1. Add to your project: composer require bkwld/upchuck:~1.0
  2. Add Upchuck as a provider in your app/config/app.php’s provider list: 'BkwldUpchuckServiceProvider',
  3. Publish the config: php artisan config:publish bkwld/upchuck

Usage

Edit the disk config setting to supply configuration information for where uploads should be moved. We are using Graham Campbell’s Flysystem integration for Laravel to instantiate Flysystem instances, so the configruation of the disk matches his configuration options for connections. As the comments in the config file mention, I recommend turning on caching if you are using any disk other than local. For both caching and other disk drivers, you will need to include other packages.

Then, to enable upload support for your models, use the BkwldUpchuckSupportsUploads trait on your model and itemize each attribute that should support uploads via the $upload_attributes property. For example:

class Person extends Eloquent {

    // Use the trait
    use BkwldUpchuckSupportsUploads;

    // Define the uploadable attributes
    protected $upload_attributes = [

        // Both the file input field and the model attribute are named "image"
        'image',

        // The input file field is named "portrait" but the model attribute is
        // named "headshot"
        'portrait' => 'headshot',
    ];

    // Since the upload handling happens via model events, it acts like a mass
    // assignment.  As such, Upchuck sets attributes via `fill()` so you can
    // control the setting.
    protected $fillable = ['image', 'headshot'];
}

Resizing images

If your app supports uploading files you are probably also dealing with needing to resize uploaded images. We (BKWLD) use our Croppa package to resize images using specially formatted URLs. If you are looking for an model-upload package that also resizes images, you might want to check out Stapler.

Deleting images

If you update a model attribute to a false-y value, Upchuck will delete the old referenced file. Thus, if your app allows users to delete files, consider using markup like:

<input type="file" name="image">
Delete file <input type="checkbox" name="image" value="">

Array-ish inputs

If your field is like this:

<input type="file" name="types[marquee][image]">

Setup your $upload_attributes like:

protected $upload_attributes = [
    'types.stats.image' => 'image',
];


License

MIT

Links