framework icon indicating copy to clipboard operation
framework copied to clipboard

[5.0] File upload is broken when submitting a form without selecting a file

Open Marwelln opened this issue 12 years ago • 27 comments

After the recent changes (I did composer update a couple of minutes ago) you can't submit a form if you have enctype="multipart/form-data" and input[type="file"] and leaves the input field empty (no file selected).

Link to error message.

Fatal error: Uncaught exception 'InvalidArgumentException' with message 'An uploaded file must be an array or an instance of UploadedFile.' in /var/www/foobar/public/liferaft/file-upload-fails/vendor/symfony/http-foundation/Symfony/Component/HttpFoundation/FileBag.php on line 59

Reproduce

1.

composer create-project laravel/laravel . dev-develop

2.

php artisan clear-compiled

3.

Set debug to true in config/app.php.

4.

Open up app/Providers/RouteServiceProvider.php and change the map method to this:

$router->group(['namespace' => 'App\Http\Controllers'], function() use ($router) {
    $router->get('/', 'HomeController@index');
    $router->put('/', 'HomeController@put');
});

5.

Add the following code to app/Http/HomeController.php:

public function put() {
    dd(\Input::all());
}

6.

Change resources/views/hello.php to this:

<!doctype html>
<html lang="en">
<body>
    <form method='post' enctype='multipart/form-data'>
        <input type='hidden' name='_method' value='put' />
        <input type='hidden' name='_token' value='<?= csrf_token(); ?>' />

        <input type='file' name='image' />
        <button>Send</button>
    </form>
</body>
</html>

If you try to submit the form without selecting a file you will get Uncaught exception 'InvalidArgumentException' with message 'An uploaded file must be an array or an instance of UploadedFile.', but if you select an image, you will get an array from Input::all().

Bad (temporary) solution

A solution is to remove an file arrays with a null value before using the SymfonyRequest::dublicate method.

Change the content of the createFromBase method from

if ($request instanceof static) return $request;

return (new static)->duplicate(

    $request->query->all(), $request->request->all(), $request->attributes->all(),

    $request->cookies->all(), $request->files->all(), $request->server->all()
);

to

if ($request instanceof static) return $request;

$files = [];
foreach ($request->files->all() as $index => $file) {
    if (null !== $file) $files[$index] = $file;
}

return (new static)->duplicate(

    $request->query->all(), $request->request->all(), $request->attributes->all(),

    $request->cookies->all(), $files, $request->server->all()
);

You can now submit the form without selecting a file.

Marwelln avatar Oct 22 '14 14:10 Marwelln

Update - check out @mantasradzevicius post of @lucasmichot 's fix below. It's more holistic and isn't based on javascript or editing core files.

+1

I've been having trouble with laravel-stapler after manually migrating and setting it up. Same result if using a multipart form type.

My solution is hilarious but doesn't require editing core files if you're okay with alienating non-js users:

$(document).ready ->
  $('.profile-form').on 'submit', (e) ->
    $photoInput = $('.profile-photo-input input')
    $photoInput.remove() if $photoInput.val() == ""
    return true

Essentially, I remove the input if the value hasn't been set to anything. Super hacky but it might fit for someone in the interim.

youanden avatar Oct 22 '14 21:10 youanden

+1

mikedugan avatar Oct 23 '14 03:10 mikedugan

+1

Hoping for a fix soon.

jeffberry avatar Oct 26 '14 01:10 jeffberry

I was about to create an issue for this too. I wrote a test case for it:

In HttpRequestTest.php:

 public function testInputWithEmptyFilename()
    {
        $invalidFiles = [
            'file' => [
                'name' => null,
                'type' => null,
                'tmp_name' => null,
                'error' => 4,
                'size' => 0
            ]
        ];

        $baseRequest = \Symfony\Component\HttpFoundation\Request::create('/?boom=breeze', 'GET', array('foo' => array('bar' => 'baz')), array(), $invalidFiles);

        $request = Request::createFromBase($baseRequest);
    }

etcinit avatar Oct 27 '14 20:10 etcinit

+1

leothelocust avatar Oct 30 '14 20:10 leothelocust

  • 1

jmfleming avatar Oct 31 '14 13:10 jmfleming

+1

MathieuDoyon avatar Nov 04 '14 12:11 MathieuDoyon

+1

mouhsinelonly avatar Nov 04 '14 13:11 mouhsinelonly

+1

davidnknight avatar Nov 06 '14 12:11 davidnknight

+1

wlkns avatar Nov 06 '14 12:11 wlkns

+1

alexandre-leites avatar Nov 07 '14 12:11 alexandre-leites

+1

jufy avatar Nov 10 '14 08:11 jufy

+1

alexleonard avatar Nov 10 '14 16:11 alexleonard

+1

ingria avatar Nov 11 '14 00:11 ingria

Thanks @youanden for the temporary JS fix. Works a treat.

alexleonard avatar Nov 11 '14 08:11 alexleonard

@alexleonard glad I could be of service.

youanden avatar Nov 11 '14 17:11 youanden

@youanden I used your fix, did the trick until a fix came out, thanks!

I've rewritten it a little with jquery to work across all file forms:

$('form[enctype="multipart/form-data"]').on('submit', function(e){
    $(this).find('input[type=file]').each(function(){
        var file = $(this);
        if (file.val() == "") file.remove();
    });
    return true;
});

colinyoung87 avatar Nov 12 '14 11:11 colinyoung87

+1 and +1 for marking it as important

lucidlemon avatar Nov 12 '14 12:11 lucidlemon

+1

gregoryduckworth avatar Nov 13 '14 10:11 gregoryduckworth

As a temp solution how to apply this fix:

  • Make a App\Http\Request class which extends Illuminate\Http\Request (example below)
  • Apply the fix either in this issue or overriding duplicate method #6256.

Example


namespace App\Http;

use Illuminate\Http\Request as LaravelRequest;

class Request extends LaravelRequest
{

    /**
     * {@inheritdoc}
     */
    public function duplicate(
        array $query = null,
        array $request = null,
        array $attributes = null,
        array $cookies = null,
        array $files = null,
        array $server = null
    ) {
        $files = array_filter((array)$files);

        return parent::duplicate(
            $query, 
            $request, 
            $attributes, 
            $cookies, 
            $files, 
            $server
        );
    }
}
  • modify your public/index.php to capture requests with your new class:
$response = $kernel->handle(
    $request = App\Http\Request::capture()
);
$response->send();
  • When a permanent fix is released revert public/index.php and remove your Request class.

Does this work: yes SideEffects: not known

mn7z avatar Nov 13 '14 21:11 mn7z