我目前正在使用此代码上传文件(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);
});
}
}
使用html:
<input #fileInput type="file" [multiple]="true" id="file-upload" size="60">
这工作正常,但由于该软件包附带的所有其他功能,我想使用ng2-file-upload。
当我输入ng2-file-upload的代码并尝试上传时,出现500错误。我100%肯定问题是键名'files',您可以在旧代码的这一行中找到它:
formData.append('files', inputEl.files.item(i));
使用ng2-file-upload时,如何将表单数据键名添加/更改为“文件”?
这是我的ng2-file-upload代码:
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);
})
}
还有html:
<input type="file" ng2FileSelect [uploader]="uploader" multiple (onFileSelected)="onFileSelected($event)" />
编辑:
我想我的问题的答案是:
public uploader: FileUploader = new FileUploader({
...
itemAlias: 'files'
...
})
...但是当我尝试上传时,我仍然收到500(内部服务器错误)...
答案 0 :(得分:-2)
500错误。尝试查看您的API端点配置是否正确。