Reputation: 3197
I'm uploading a multi file array to my server in Laravel.
When I log the files using $request->file('files')
I get:
[2018-11-12 16:10:03] local.DEBUG: array (
0 =>
Illuminate\Http\UploadedFile::__set_state(array(
'test' => false,
'originalName' => 'test-pdf.pdf',
'mimeType' => 'application/pdf',
'error' => 0,
'hashName' => NULL,
)),
1 =>
Illuminate\Http\UploadedFile::__set_state(array(
'test' => false,
'originalName' => 'test-pdf.pdf',
'mimeType' => 'application/pdf',
'error' => 0,
'hashName' => NULL,
)),
2 =>
Illuminate\Http\UploadedFile::__set_state(array(
'test' => false,
'originalName' => 'test-pdf.pdf',
'mimeType' => 'application/pdf',
'error' => 0,
'hashName' => NULL,
)),
)
I want to access each file in the array and get the pathname like so:
$files = $request->files;
foreach ($files as $key => $file) {
Log::debug($file->getPathName());
}
However this throws the following error:
local.ERROR: Call to a member function getPathName() on array {"exception":"[object] (Symfony\\Component\\Debug\\Exception\\FatalThrowableError(code: 0): Call to a member function getPathName() on array at /home/vagrant/Projects/business-risk-portal/app/Http/Controllers/FileController.php:68)
How can access the file path for each of those uploaded files?
UPDATE If I try this:
$files = $request->files;
foreach ($files as $key => $file) {
$temp_path = $request->file('tmp.' . $key);
Log::debug($temp_path->getPathName());
}
I get:
Call to a member function getPathName() on null {"exception":"[object] (Symfony\\Component\\Debug\\Exception\\FatalThrowableError(code: 0): Call to a member function getPathName() on null at /home/vagrant/Projects/business-risk-portal/app/Http/Controllers/FileController.php:69)
Upvotes: 0
Views: 4348
Reputation: 35347
$request->files
will return a multi-dimensional array of all files, while $request->file('files')
will return an array of only the files relating to the files
input.
Upvotes: 2
Reputation: 1856
Here is what worked for me:
Server side:
$files = $request->file('myfiles');
foreach($files as $file) {
$target = $file->move(storage_path('files'), $file->getClientOriginalName());
$path = $target->getPath() . DIRECTORY_SEPARATOR . $target->getFileName();
}
View:
<form method="post" action="/myfiles" enctype="multipart/form-data">
{{csrf_field()}}
<input type="file" name="myfiles[]" class="form-control" multiple />
<button type="submit" class="btn btn-success">Save</button>
</form>
Upvotes: 0