【发布时间】:2021-03-05 18:54:40
【问题描述】:
我在 Angular 7 项目上工作,我遇到了上传数据时出现错误属性名称的问题。
我先选择文件,然后按下按钮上传
按下按钮上传后,我收到以下错误:
core.js:4197 ERROR TypeError: Cannot read property 'name' of undefined
at UploadComponent.uploadFile (upload.component.ts:96)
at UploadComponent_Template_button_click_5_listener (upload.component.html:6)
at executeListenerWithErrorHandling (core.js:14286)
at wrapListenerIn_markDirtyAndPreventDefault (core.js:14321)
at HTMLButtonElement.<anonymous> (platform-browser.js:582)
at ZoneDelegate.invokeTask (zone-evergreen.js:399)
at Object.onInvokeTask (core.js:27394)
at ZoneDelegate.invokeTask (zone-evergreen.js:398)
at Zone.runTask (zone-evergreen.js:167)
at ZoneTask.invokeTask [as invoke] (zone-evergreen.js:480)
我在下面一行收到此错误:
formData.append('file', fileToUpload, fileToUpload.name);
完整的上传代码
component.html
<div class="col-md-3">
<input type="file" #file placeholder="Choose file" multiple>
<button type="button" class="btn btn-success" (click)="uploadFile(file)">Upload File</button>
</div>
组件.ts
public uploadFile = (files) => {
if (files.length === 0) {
return;
}
let fileToUpload = <File>files[0];
const formData = new FormData();
formData.append('file', fileToUpload, fileToUpload.name);
this.http.post('https://localhost:44396/api/ApprovalQuality/', formData, {reportProgress: true, observe: 'events'})
.subscribe(event => {
if (event.type === HttpEventType.UploadProgress)
{
this.progress = Math.round(100 * event.loaded / event.total);
}
else if (event.type === HttpEventType.Response) {
this.message = 'Upload success.';
this.onUploadFinished.emit(event.body);
}
});
}
请问如何解决这个错误?
【问题讨论】:
-
当你在
console.log(fileToUpload)里面uploadFile()函数时你会得到什么
标签: javascript typescript angular7 angular-directive angular-components