I’m making an app where users can upload multiple photos.
When they open <input type="file" multiple>
, I then listen on change event, create a faux array of those files and dynamically create images for the user to preview them before uploading.
fauxArray = Array.from(e.target.files);
for (image of fauxArray) {
let newImage = document.createElement("IMG");
newImage.src = URL.createObjectURL(image);
}
I do this so the user can decide not to upload all of them and maybe remove some before the actual saving on the server. So I have a button next to each image, and if they use it, I alter the fauxArray accordingly.
The problem happens when I try to add this to fetch request.
const formData = new FormData();
formData.append( 'memoryPhotos', fauxArray ); // <- HERE
formData.append( 'memoryTitle', packageTitle );
formData.append( 'memoryDescription', packageDescription );
fetch("gui/save.php", {
method: "post",
body: formData,
})
Because on PHP side, when I read it with $_POST['memoryPhotos']
, I just get the string [object File],[object File]
(if there were 2 files etc.).
How to attach my array of files to formdata to be read on server? Or am I using a wrong format for the duplicated images from input?
2
Answers
You should read the photo’s data and serialize them for example as data urls. To post a JS object you need to serialize it to JSON and use
json_decode()
on the php side. You can useawait Promise.all
without wrapping in anasync
function in JS modules.But better attach the files to the FormData directly:
https://developer.mozilla.org/en-US/docs/Web/API/FormData/append
Based upon your description of the app and the snippets of code shown perhaps the following will be of interest. The above fails as you simply assign the entire "fauxArray" directly as a value to the FormData object rather than the individual files themselves contained within that array. The solution is to iterate through that array and add each item as the value of an array-like field – below however to ease the deletion of files prior to upload the "fauxArray" is declared as an Object literal "faux" – so that one can use
delete
on the object rather than array slice / splice etc