angular - 如何使用 Angular 上传相同的文件?
问题描述
我使用以下代码在 Angular 中上传文件:
HTML
<div class="form-group">
<label for="file">Choose File</label>
<input type="file"
id="file"
(change)="uploadRenewals($event.target.files)">
</div>
打字稿
fileToUpload: File = null;
uploadRenewals(files: FileList) {
console.log('Uploading starts...', files);
const formData: FormData = new FormData();
this.fileToUpload = files.item(0);
formData.append('file', this.fileToUpload, this.fileToUpload.name);
this._docService.uploadRenewals(formData)
.pipe(take(1))
.subscribe((response: RenewalsResponse) => {
console.log('Response is', response);
}, (error) => {console.log(error);});
服务
uploadRenewals(formData: FormData) {
return this._http.post(this.baseUrl + '/docs/uploadRenewals', formData, { responseType: 'json' })
.catch(this.errorHandler);
}
这里的事情是,当我每次上传不同的文件时它都有效,但是当我尝试上传相同的文件时,什么都没有被触发,并且该uploadRenewals()
函数永远不会被调用。
我还注意到,当我(change)="uploadRenewals($event.target.files)
第三次打开窗口时(在我第二次选择相同的文件并且没有发生任何事情之后)并在不选择任何文件的情况下关闭它,uploadRenewals()
被调用并console
显示以下错误:
ERROR TypeError: Cannot read property 'name' of null
知道发生了什么以及如何解决这个问题吗?
解决方案
解释 :
您需要的是在每次上传后清除输入文件元素,如果您关闭对话框并且使用空事件触发事件(更改) ,那么当涉及到这一行时,第二个问题是:
formData.append('file', this.fileToUpload, this.fileToUpload.name);
this.fileToUpload 为空。
解决方案 :
TS:
import {
Component,
OnInit,
ViewChild,
ElementRef
} from '@angular/core';
@ViewChild('fileInput', {
static: false
}) fileInput: ElementRef;
fileToUpload: File = null;
uploadRenewals(files: FileList) {
console.log('Uploading starts...', files);
const formData: FormData = new FormData();
this.fileToUpload = files.item(0);
if (this.fileToUpload) { // this condition to avoid your the error that you mentioned
formData.append('file', this.fileToUpload, this.fileToUpload.name);
this._docService.uploadRenewals(formData)
.pipe(take(1))
.subscribe((response: RenewalsResponse) => {
console.log('Response is', response);
this.fileInput.nativeElement.value = null; //this clears the input file to let the event (change) fire again so you can upload the same file again
}, (error) => {
console.log(error);
});
}
}
HTML:
<div class="form-group">
<label for="file">Choose File</label>
<input #fileInput type="file"
id="file"
(change)="uploadRenewals($event.target.files)">
</div>
推荐阅读
- python - 无法在 AWS ec2 中安装 pyodbc 包
- python - Transforming python code to HDL using hls4ml
- python - 在 Google colab 中使用 jupyter_nbextensions_configurator
- javascript - 如何在反应中更新表列的数据?
- html - MODX 将 RESOURCES 获取为 html
- javascript - 本地范围调用如何在其自身功能之外工作?- jQuery
- powershell - 尝试使用 invoke-command、chocolatey 和 7zip 解压缩文件
- javascript - 在Vue中更改对象时不呈现div
- c# - 如何使用 C# 比较两个图像并获得透明背景图像?
- arrays - 使用 Node Js 和 ForEach 循环在 cloudinary 中多次上传