I have implemented the following code for file upload in Angular 2+:
upload() {
let inputEl: HTMLInputElement = this.inputEl.nativeElement;
let fileCount: number = inputEl.files.length;
let formData = new FormData();
if (fileCount > 0) { // a file was selected
for (let i = 0; i < fileCount; i++) {
formData.append('files', inputEl.files.item(i));
}
this.http.post(mySecretUrl, formData, {observe: 'response'}).subscribe(err => this.handleError(err), resp => {
console.log(resp);
});
}
}
Using html:
<input #fileInput type="file" [multiple]="true" id="file-upload" size="60">
While this code works well, I wanted to switch to ng2-file-upload for additional features it offers.
However, when I integrated the ng2-file-upload code and attempted to upload a file, I encountered a 500 error. After examining the code, I realized that the issue lies in the key name 'files' found in this line of the original code:
formData.append('files', inputEl.files.item(i));
How can I modify the form-data key name to 'files' when using ng2-file-upload?
Here is my ng2-file-upload code:
function readBase64(file): Promise<any> {
var reader = new FileReader();
var future = new Promise((resolve, reject) => {
reader.addEventListener("load", function () {
resolve(reader.result);
}, false);
reader.addEventListener("error", function (event) {
reject(event);
}, false);
reader.readAsDataURL(file);
});
return future;
}
const URL = 'mySecretUrl';
private uploader:FileUploader = new FileUploader({
url: URL,
disableMultipart:true
});
public hasBaseDropZoneOver:boolean = false;
fileObject: any;
public fileOverBase(e:any):void {
this.hasBaseDropZoneOver = e;
}
public onFileSelected(event: EventEmitter<File[]>) {
const file: File = event[0];
console.log(file);
readBase64(file)
.then(function(data) {
console.log(data);
})
}
In addition to the accompanying html:
<input type="file" ng2FileSelect [uploader]="uploader" multiple (onFileSelected)="onFileSelected($event)" />
EDIT:
I believe the solution to my question is:
public uploader: FileUploader = new FileUploader({
...
itemAlias: 'files'
...
})
Despite implementing the suggested change, I am still facing a 500 internal server error during the upload process.