I'm after such flow:
I am stuck on the step 2. For some reason, my PHP does not get the File object.
Here is my code.
a simple form with a div#uploadZone
pretending drop zone for user's files.
// file selected
$("#files").change(function() {
for (var index = 0; index < $('#files')[0].files.length; index++) {
var fd = new FormData();
fd.append('file', $('#files')[0].files[index]);
fd.append('item', $('#record').val());
// formData for console output
console.table([...fd]);
$(document).uploadPhoto($('#files')[0].files.length - 1, index, [...fd]);
}
});
(function($) {
$.fn.uploadPhoto = function(count, loopIndex, formData) {
var index = loopIndex;
var total = count;
$.ajax({
url: "/ajax/photo/new",
method: "post",
data: formData,
cache: false,
contentType: false,
processData: false,
}).done(function(msg) {
// show uploaded photos
console.log('OK');
}).fail(function(jqXHR, msg) {
console.log('ERROR');
});
}
}(jQuery));
<form action="/photo/new" id="uploadDataForm" method="post" enctype="multipart/form-data">
<fieldset class="pb-5">
<div class="text-center p-4 idle" id="uploadZone">Drag & drop here</div>
<input class="d-none" type="file" name="file" id="file">
<div class="mt-4 pt-2 d-flex flex-wrap align-items-stretch" id="gallery-wrapper"></div>
<input type="file " id="files " name="files[] " multiple>
<input type="hidden " id="record " name="record " value="a1 ">
</fieldset>
</form>
When looking at the console, the result of console.table([...fd]) is:
| Index | 0 | 1 |
|-------|------|----|
| 0 |'file'|File|
| 1 |'item'|'a1'|
By expanding the details of the entry under [0] index, I'm able to see File meta data, i.e.:
However, when I inspect data on PHP:
// Slim4 framework
$uploadedFiles = $request->getUploadedFiles();
$this->logger->debug(var_dump($uploadedFiles));
// or like this
var_dump($_FILES));
Both outputs: null
I have no idea why output is null. Any ideas mates? I'm going crazy with this.
You have an error in your code, pass the FormData
to your uploadPhoto
properly. Also delete spaces from your HTML attributes otherwise the JS code wouldn't work at all (On the other hand the OP was able to POST. so probably spaces are just wrong example data):
$(document).uploadPhoto($('#files')[0].files.length - 1, index, fd);