angular - ng2-file-upload: How to change the form-data name for file upload
问题描述
I am currently using this code for file upload (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);
});
}
}
With html:
<input #fileInput type="file" [multiple]="true" id="file-upload" size="60">
This works fine, but I wanted to use the ng2-file-upload because of all the extra goodies that comes along with that package.
When I enter my code for ng2-file-upload and try to upload I get a 500 error. I am 100% sure the problem is the key name 'files' which you will find in this line in the old code:
formData.append('files', inputEl.files.item(i));
How can I add/change the form-data key name to 'files' when using ng2-file-upload?
This is btw my code for 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);
})
}
And the html:
<input type="file" ng2FileSelect [uploader]="uploader" multiple (onFileSelected)="onFileSelected($event)" />
EDIT:
I guess the answer to my question is:
public uploader: FileUploader = new FileUploader({
...
itemAlias: 'files'
...
})
...But I still get a 500 (internal server error) when I try to upload...
解决方案
如果服务器端出现问题,通常会发生 500 错误。尝试查看您的 API 端点是否配置正确。
推荐阅读
- ruby-on-rails - 未定义方法 `-' for nil:NilClass 用于现有字段的活动记录回调
- gatsby - Gatsby 构建错误“文档未定义”仅在 Netlify 上
- ios - iOS - Xcode 不作为 -> 动作按钮未“执行”定义的动作
- python - 如何在树视图中显示父目录?
- jquery - 在 Kendo jQuery 网格中,您如何识别向用户显示哪些行?
- google-apps-script - 谷歌表格 dd/mm/yyyy 到 mm/dd/yyyy 日期格式
- neural-network - Inception-v1 与 Inception-Resnet-V1
- shell - 如何用户期望并发送请求和睡眠
- leaflet - 如何将多边形坐标添加到现有的 geoJSON 文件?
- cassandra - Opscenter.rollup_state 表的卡住压缩