I’m trying to upload multiple files but I don’t know how to. I can successfully upload a file or image using the code below but not multiple files. How can I upload multiple files instead?
onUploadChange(ev) {
let myFile = ev.target.files;
//let url = URL.createObjectURL(myFile);
for (let i=0; i<myFile.length; i++) {
this.readFile(myFile[i]);
}
But I should have been more clear. What I want to do is if a user uploads 3 items I want to append each to formData so that I can later send all 3 to my server at the same time. Should I use FormData for this or is there a better way?
Personally, I consider JSON far superior to FormData, in part because of how simple it makes this sort of issue, as it has built-in support for arrays. In the end, this is all completely dependent on what the server is capable of accepting.
I think you should consider using ng2-file-upload. It’s recommended by a lot of places, for example Cloundinary uses it in their official Angular 2 sample project. Your code looks very Javascripty, and not very Angular-2’'y. The more you can Angularize it, the better off you’ll be. Also, making your code Observable-based instead of callback-based might simplify things a lot.
So first the first way after I change that line instead of appending to formdata would I do something like
data = [];
onUploadChange(ev) {
let myFile = ev.target.files;
//let url = URL.createObjectURL(myFile);
for (let i=0; i<myFile.length; i++) {
this.readFile(myFile[i]);
}
private readFile(file: any) {
const reader = new FileReader();
reader.onloadend = () => {
this.data.push(reader.result, file.type);
};
reader.readAsArrayDataURL(file);
}
And for the second option I’m not really sure how I would do that… I found this example online
var bufferToBase64 = function (buffer) {
var bytes = new Uint8Array(buffer);
var len = buffer.byteLength;
var binary = "";
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa(binary);
};
Looking through how ng2-file-upload works at the end of the day I think I would bestuck in the same place trying to figure out how to send multiple files in one request