You are not logged in.

Important Note: This forum is being archived and will be completely locked down on the 7th of February. The new forum can be found at http://laravel.io.

Announcement

    Laravel 4 Advanced Architecture: Book Now On Sale

#1 2013-05-29 16:53:23

msurguy
Artisan
From: United States
Registered: 2012-04-11
Posts: 415
Website

File uploads in Laravel 4

This script can work with multi file uploads that I have documented in my blog post on AJAX file uploads - http://maxoffsky.com/code-blog/howto-aj … n-laravel/ basically adapting that method (using DropzoneJS but could be used with any other file upload frontend solution) to the new Laravel 4 file operations.

Create folder 'uploads' in the 'public'

Then, in your controller where you POSTing your file uploads, insert the following code:

$file = Input::file('file'); // your file upload input field in the form should be named 'file'

$destinationPath = 'uploads/'.str_random(8);
$filename = $file->getClientOriginalName();
//$extension =$file->getClientOriginalExtension(); //if you need extension of the file
$uploadSuccess = Input::file('file')->move($destinationPath, $filename);
 
if( $uploadSuccess ) {
   return Response::json('success', 200); // or do a redirect with some message that file was uploaded
} else {
   return Response::json('error', 400);
}

This will save your uploaded file in a randomly named folder in the uploads folder.

There are a few ways to upload files in AJAX fashion, you can use the following methods/plugins :
- http://blueimp.github.io/jQuery-File-Upload/
- http://www.dropzonejs.com/
- http://malsup.com/jquery/form/#file-upload

I have tested all of these extensively and the one that works really well in most browsers is the last one - it uses iFrame transfer method where the file is POSTed to an invisible iFrame so that it looks like AJAX uploads but really it's not. The advantage of this method is that even very old browsers understand iFrames and work well with this method.

I am using the dropzonejs.com plugin and the code I provided above on my Laravel application for temporary file sharing :
http://filegr.am

UPDATE:
Make sure that your form that uploads the file contains 'files'=>true setting like so:

{{ Form::open(array('url' => 'foo/bar', 'files' => true)) }}

Enjoy and feel free to ask questions!

Last edited by msurguy (2013-09-20 18:31:08)

Offline

#2 2013-05-29 17:16:34

Dave_N
Artisan
From: Denver, CO
Registered: 2013-05-23
Posts: 24

Re: File uploads in Laravel 4

Awesome! - One question...

How well does the invisible iFrame idea work on most mobile phones? The reason I ask this, i could make an app where the user can upload say a picture of themselves that is already on their phone. Not sure the current state of iframes on most phones or if this is a problem or not?

OR perhaps as a newbie I am way off base with this question?

Last edited by Dave_N (2013-05-29 17:17:14)

Offline

#3 2013-05-29 17:47:57

simondavies
Artisan
From: Plymouth, UK
Registered: 2013-03-18
Posts: 358

Re: File uploads in Laravel 4

How well does it work with zip files rather than single / multiple files, as it would be great as i currently had to use the normal means to upload a zip and as they are big i cannot get the feedback that these plugins give.


A developer of the web and all things mobile...

Offline

#4 2013-05-29 18:02:30

msurguy
Artisan
From: United States
Registered: 2012-04-11
Posts: 415
Website

Re: File uploads in Laravel 4

I believe iFrames are supported by all mobile and desktop browsers.
I tested the iFrame method with iOS 6 Safari and Chrome on Android devices and Android 3+ native browsers and it works well.

Dave_N wrote:

Awesome! - One question...

How well does the invisible iFrame idea work on most mobile phones? The reason I ask this, i could make an app where the user can upload say a picture of themselves that is already on their phone. Not sure the current state of iframes on most phones or if this is a problem or not?

OR perhaps as a newbie I am way off base with this question?

Offline

#5 2013-05-29 18:16:42

msurguy
Artisan
From: United States
Registered: 2012-04-11
Posts: 415
Website

Re: File uploads in Laravel 4

It doesn't matter what files are uploaded, it should all work well.

One thing you have to check on your PHP installation is the max upload size and maximum post size. Those can be set in the ini file and if you are planning to do large size file uploads you have to have plenty of RAM on your server.

simondavies wrote:

How well does it work with zip files rather than single / multiple files, as it would be great as i currently had to use the normal means to upload a zip and as they are big i cannot get the feedback that these plugins give.

Offline

#6 2013-05-29 18:35:26

RickM
Artisan
Registered: 2012-09-27
Posts: 49

Re: File uploads in Laravel 4

Damn wish I'd seen this a couple of days ago. I just finished building a KCFinder type clone (file/folder manager) in L4 and used jquery file uploader (http://blueimp.github.io/jQuery-File-Upload/). It was a complete pain in the ass to work with.

Offline

#7 2013-05-29 20:25:00

memory
Apprentice
Registered: 2013-05-29
Posts: 3

Re: File uploads in Laravel 4

function move($directory, $name = null) return throw new FileException. it should be in block try catch

Offline

#8 2013-05-29 21:10:13

codenamegary
Moderator
From: Toronto, ON
Registered: 2012-03-08
Posts: 733
Website

Re: File uploads in Laravel 4

Dave_N wrote:

Awesome! - One question...

How well does the invisible iFrame idea work on most mobile phones? The reason I ask this, i could make an app where the user can upload say a picture of themselves that is already on their phone. Not sure the current state of iframes on most phones or if this is a problem or not?

OR perhaps as a newbie I am way off base with this question?

Something may have changed but last I checked you couldn't upload a file from the browser on an iPhone without a 3rd party app and a lot of hassle. Android is probably fine.


PointLocker - The Ubiquitous Mobile Rewards Platform
http://www.twitter.com/codenamegary
Simple Asset Collections for Laravel 4
https://bitbucket.org/codenamegary/l4sacs

Offline

#9 2013-05-29 21:52:21

msurguy
Artisan
From: United States
Registered: 2012-04-11
Posts: 415
Website

Re: File uploads in Laravel 4

Things have changed in iOS 6. The file uploads work just like you would expect them.
If you have iOS 6 please go to one of my sites to test it :
http://missingpetflyer.com (made with Laravel 4 and Blueimp file uploader)
http://fldrp.me (uses dropzonejs.com)

File uploads work just fine on iOS 6 browser with no apps smile
One thing to keep in mind when you upload multiple pictures from iPhone - all of them will have the same file name - "image" so what I do is I have a table column called "alias" and I keep the original file name in that DB column and on upload I modify the file name to something random like ajdfuHDfjf.jpg, dfoUydfjdlsld.jpg , etc. That way I prevent collisions of file names and people can upload unlimited number of files with the same name.

codenamegary wrote:
Dave_N wrote:

Awesome! - One question...

How well does the invisible iFrame idea work on most mobile phones? The reason I ask this, i could make an app where the user can upload say a picture of themselves that is already on their phone. Not sure the current state of iframes on most phones or if this is a problem or not?

OR perhaps as a newbie I am way off base with this question?

Something may have changed but last I checked you couldn't upload a file from the browser on an iPhone without a 3rd party app and a lot of hassle. Android is probably fine.

Offline

#10 2013-06-11 21:11:46

PolyPlanker
Artisan
Registered: 2012-08-08
Posts: 21

Re: File uploads in Laravel 4

I've tired to duplicate this in a simple testing page (source code below) but I am getting the following error

Call to a member function getClientOriginalName() on a non-object

Blade Template

@extends('frontend/layouts/default')

@section('content')
{{ Form::open(array('action' => 'UploadController@postImage')) }}
	{{ Form::token() }}
	{{ Form::file('file') }}
	{{ Form::submit('Click Me!') }}
{{ Form::close() }}
@stop

UplaodController

<?php
class UploadController extends AuthorizedController {
	public function postImage()
	{
		$file = Input::file('file'); // your file upload input field in the form should be named 'file'

		$destinationPath = 'uploads/'.str_random(8);
		$filename = $file->getClientOriginalName();
		//$extension =$file->getClientOriginalExtension(); //if you need extension of the file
		$uploadSuccess = Input::file('file')->move($destinationPath, $filename);
		 
		if( $uploadSuccess ) {
		   return Response::json('success', 200); // or do a redirect with some message that file was uploaded
		} else {
		   return Response::json('error', 400);
		}
	}
}

Any help is greatly appreciated!

Chris

Offline

#11 2013-06-11 22:03:03

msurguy
Artisan
From: United States
Registered: 2012-04-11
Posts: 415
Website

Re: File uploads in Laravel 4

You need to add files=> true to your form :

{{ Form::open(array('action' => 'UploadController@postImage','files'=>true)) }}

Try this and let me know if it works!

Offline

#12 2013-06-11 22:14:43

PolyPlanker
Artisan
Registered: 2012-08-08
Posts: 21

Re: File uploads in Laravel 4

That was it, everything is working now! I hate the simple rookie mistakes ;o)
Thank you.

Chris

Offline

#13 2013-06-11 23:09:45

msurguy
Artisan
From: United States
Registered: 2012-04-11
Posts: 415
Website

Offline

#14 2013-06-19 21:49:06

nhtet
Apprentice
Registered: 2013-06-19
Posts: 2

Re: File uploads in Laravel 4

Thanks for the post.
I would like to ask what is the best practice to store the sensitive user upload documents? In most of the tutorials, I see that they are creating a folder under public folder to store the uploaded files but wouldn't it be a security issue?
Thanks.

Offline

#15 2013-06-19 22:58:43

msurguy
Artisan
From: United States
Registered: 2012-04-11
Posts: 415
Website

Re: File uploads in Laravel 4

You are not required to store the uploads in the public folder but that would make the retrieval process of the files a bit more complicated since they are not publicly available. One way is to store files on protected Amazon S3 storage, another way is just have a folder in the root of your application (one level up from public) with the uploads and somehow stream the files on download (maybe even Laravel's download response could work : http://laravel.com/docs/responses#special-responses ).

I would say this is a ground for experimentation as I didn't have a need for ultra secure file storage solution...

Offline

#16 2013-06-21 05:34:21

nhtet
Apprentice
Registered: 2013-06-19
Posts: 2

Re: File uploads in Laravel 4

Thanks ! I will give it a try.

Offline

#17 2013-06-25 17:59:23

simondavies
Artisan
From: Plymouth, UK
Registered: 2013-03-18
Posts: 358

Re: File uploads in Laravel 4

msurguy wrote:

It doesn't matter what files are uploaded, it should all work well.

One thing you have to check on your PHP installation is the max upload size and maximum post size. Those can be set in the ini file and if you are planning to do large size file uploads you have to have plenty of RAM on your server.


Thanks for the reply (sorry late reply from me been busy and it did not let me kwno u had a reply) I already have an app that i use to upload a zip files with hi res images that then unzips,  then crops dependant the  crop setting, then also  creates thumbnails etc,  so i have  dealt with the max upload size before etc, but will have a loo at this when i get to this particular part of my app redesign using laravel

thanks again.


A developer of the web and all things mobile...

Offline

#18 2013-07-05 16:43:59

ghprod
Artisan
From: Indonesia
Registered: 2012-08-16
Posts: 477
Website

Re: File uploads in Laravel 4

Thanks Mrsurguy, always help with community like always wink

Offline

#19 2013-07-05 17:55:51

msurguy
Artisan
From: United States
Registered: 2012-04-11
Posts: 415
Website

Re: File uploads in Laravel 4

You're welcome! Love to share what I have learned!

Offline

#20 2013-07-09 13:41:16

Maromo
Apprentice
Registered: 2013-07-09
Posts: 4

Re: File uploads in Laravel 4

msurguy wrote:

You need to add files=> true to your form :

{{ Form::open(array('action' => 'UploadController@postImage','files'=>true)) }}

Try this and let me know if it works!


Thanks a lot Msurguy but it didn't work for me. This is my simple testing page:

Blade Template:

    {{ Form::model($union, array('method' => 'put', 'files'=>true, 'route' => array('admin.unions.update', $union->id))) }}
 
                
            {{ Form::token() }}
            {{ Form::file('file') }}
            {{ Form::submit('Click Me!') }}

            {{ Form::label('title', 'Title') }}
            
            {{ Form::text('title', $union->title, array('class' => 'input-100')) }}
            
            {{ Form::label('body', 'Content') }}
            
            {{ Form::textarea('body', $union->body, array('class' => 'input-100')) }}

            {{ Form::submit('Save', array('class' => 'btn btn-success btn-save btn-large')) }}
            <a href="{{ URL::route('admin.unions.index') }}" class="btn btn-large">Cancel</a>
        
 
    {{ Form::close() }}

UnionsController:

	public function update($id)
	{


		$file = Input::file('file'); // your file upload input field in the form should be named 'file'

		$destinationPath = 'uploads/'.str_random(8);
		$filename = $file->getClientOriginalName();
		$extension =$file->getClientOriginalExtension(); //if you need extension of the file
		$uploadSuccess = Input::file('file')->move($destinationPath, $filename);
		 
		

		$validation = new UnionValidator;
 
        if ($validation->passes())
        {
            $union = \Unions::find($id);
            $union->title   = Input::get('title');
            $union->slug    = Str::slug(Input::get('title'));
            $union->body    = Input::get('body');
            $union->user_id = Sentry::getUser()->id;
            $union->save();
 
            Notification::success('The union was saved.');
 
            return Redirect::route('admin.unions.edit', $union->id);
        }
 
        return Redirect::back()->withInput()->withErrors($validation->errors);
	}

Any help is greatly appreciated.

Best

Offline

#21 2013-07-15 10:26:48

mahami
Artisan
Registered: 2013-05-28
Posts: 13

Re: File uploads in Laravel 4

hi max, i use your script exactly the same but i got this error  "Call to a member function getClientOriginalName() on a non-object"
thank you.

Offline

#22 2013-07-15 11:41:54

Barryvdh
Artisan
From: Eindhoven, Netherlands
Registered: 2012-10-22
Posts: 861
Website

Re: File uploads in Laravel 4

Do you have the correct fieldname? And do you have opened your form for files (or set the enctype to multipart/form-data)?


Laravel IDE Helper Generator (Generates auto-completion for phpStorm/NetBeans/Sublime CodeIntel)
Laravel PHP Debugbar (Profiler/Web toolbar for Debug/Database/Views and Ajax/Redirect support)

Offline

#23 2013-07-15 13:29:35

mahami
Artisan
Registered: 2013-05-28
Posts: 13

Re: File uploads in Laravel 4

yes, i use the correct fieldname and 'file'=> true for open form, but i don't understand the last part, can you explain that?please.thank you

Offline

#24 2013-07-15 21:42:24

msurguy
Artisan
From: United States
Registered: 2012-04-11
Posts: 415
Website

Re: File uploads in Laravel 4

mahami wrote:

hi max, i use your script exactly the same but i got this error  "Call to a member function getClientOriginalName() on a non-object"
thank you.

Please post the form that is in your blade template.

Offline

#25 2013-07-21 22:51:25

mahami
Artisan
Registered: 2013-05-28
Posts: 13

Re: File uploads in Laravel 4

I resolve the problem by adding the 'enctype' => 'multipart/form-data' in my form. thank you

Last edited by mahami (2013-07-21 22:51:52)

Offline

Board footer

Powered by FluxBB

');