PHP-FileUpload
PHP-FileUpload copied to clipboard
Multiple File Uploads
Hey,
is it possible to upload mutiple files from an file input with multiple attribute?
I've tried it like this:
**
$upload->from('file1');
$upload->from('file2');
$upload->from('file3');
$upload->from('file4');
**
but the library keeps uploading just one single file.
Thanks, excellent question!
Uploading multiple files with separate file inputs, i.e. two or more HTML elements with different name attributes and without the multiple attribute, is possible.
But uploading multiple files with a single file input, i.e. one HTML element whose name attribute has got [] appended and which has the multiple attribute set, is not supported yet, unfortunately.
In order to add support for this, we’ll have to modify the class FileUpload and its method save. If we see that the error attribute (or size or name or tmp_name) is actually an array instead of a scalar value (string or int), we have to run the whole code in that method in a loop, iterating over the individual files uploaded with that name.
Perhaps that should even be a separate new method, e.g. saveMultiple, because we’ll have to return File[] instead of File in that case.
As a workaround, I use the code below (catch left out for this post).
Not the nicest way, but it works. The HTML input field is: <input name="fileToUpload_multiple[]" type="file" multiple>
$files = array();
foreach ($_FILES['fileToUpload_multiple'] as $k => $l) {
foreach ($l as $i => $v) {
if (!array_key_exists($i, $files)) {
$files[$i] = array();
}
$files[$i][$k] = $v;
}
}
foreach ($files as $file) {
$_FILES['fileToUpload'] = $file;
$upload = new \Delight\FileUpload\FileUpload();
$upload->withTargetDirectory('/path/to/target');
$upload->from('fileToUpload');
try {
$uploadedFile = $upload->save();
}
}
@nssnl Thanks a lot for sharing your solution! I had never thought about manipulating $_FILES directly (temporarily) and then running a normal (single-file) upload with that. That’s interesting. Good to know there’s a workaround for now that you can use with this library. With the final implementation here in this library, we won’t have to modify $_FILES, of course, and can use internal copies.