Laravel 5, attempting multi-file upload, Request::

2019-04-11 23:08发布

问题:

I'm attempting to get multiple files uploaded using the same key using Laravel 5's Request facade. From what I've read elsewhere, the correct way to do this is to call Request::file() without passing a parameter to the ::file() method.

However, this only seems to return the last file sent in the request.

Headers

POST /test/service/upload HTTP/1.1
Host: www.****.dev
X-CSRF-TOKEN: 2DQBuTuy50EELFen5vXFaOv1cyXICmAISUx8LoCS
Cache-Control: no-cache

----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="photo"; filename="10464005_10152969193248906_6272325120604924631_n.jpg"
Content-Type: image/jpeg


----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="photo"; filename="10458555_10152969192978906_1569926627111581344_n.jpg"
Content-Type: image/jpeg


----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="photo"; filename="10365774_10152969188498906_1884545544754633531_n.jpg"
Content-Type: image/jpeg


----WebKitFormBoundaryE19zNvXGzXaLvS5C

PHP

    $files = Request::file();
    $names = [];

    foreach ($files as $file) {
        $names[] = $file->getClientOriginalName();
    }
    return $names;

Response

[
    "10365774_10152969188498906_1884545544754633531_n.jpg"
]

Is there any kind of configuration or headers that I have to set for this work appropriately? If it helps, this will be an AJAX based request and I've been using the Google Chrome extension "Postman" to test this.

Any help would be greatly appreciated!

回答1:

use array of file element as html like follow

<input type="file" name="photo[]">
<input type="file" name="photo[]">

add enctype attribute in form and in laravel to get file use the key of the file as follow

$files = Request::file('photo');
    $names = [];

    foreach ($files as $file) {
        $names[] = $file->getClientOriginalName();
    }
    return $names;

according to me it should work.