This and this answer is my motivation for trying to convert an object
to file
type and append to FormData as so:
var fileBag = new FormData();
fileArray.forEach(function(element) {
file_name = element.name;
file_type = element.type;
var file = new File([element], file_name, {type:file_type});
console.log("file type= ", typeof file); // o/p is object
fileBag.append(file_name, file);
});
When I tried the same, typeof newly created file is object (I expect it to be file) after being converted to file.
File
object is same before and after conversion as so:
File
lastModified: 1543472205025
lastModifiedDate: Thu Nov 29 2018 11:46:45 GMT+0530 (India Standard Time) {}
name: "testFile.xlsx"
size: 1119910
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
webkitRelativePath: ""
__proto__: File
This is how I am sending via Ajax
$.ajax({
url: '/project/url/',
type: 'POST',
data: {'file': fileBag},
enctype: 'multipart/form-data',
processData: false,
contentType: false,
dataType: "json",
success: function (data) {
console.log("data= ",data);
},
error: (error) => {
console.log(JSON.stringify(error));
}
});
I have tried this in both Django
and PHP
. I am getting empty arrays. My question is:
1) Will the typeof
before and after conversion will be the same?
2) How can I send file object arrays to backend? Is there any other solution?
Here is my codepen of the same.
Edit: Codepen code
var fileArray = [];
var fileBag = new FormData();
function handleFileUpload(event)
{
var fileUploadButtonId = event.currentTarget.id;
var files = document.getElementById(fileUploadButtonId).files;
var fileBag = new FormData();
var arrayOfAllUploadedFiles = Array.from(files);
for(var i=0; i<arrayOfAllUploadedFiles.length; i++)
{
fileArray.push(arrayOfAllUploadedFiles[i]);
}
fileArray.forEach(function(element) {
file_name = element.name;
file_type = element.type;
var file = new File([element], file_name, {type:file_type});
console.log("file type= ", typeof file); // o/p is object. // o/p is object. Shouldn't this be 'file'?
fileBag.append(file_name, file);
alert("filebag= ",fileBag); // this is empty
});
}