Angular 上传文件 可参考Angular2使用ng2-file-upload上传文件浏览器
这里记录在开发过程当中遇到的问题:app
根据设计要求,须要添加删除按钮,用于删除选择的文件。
在开发的过程当中发现删除后,不能选择上一次选择的相同的文件,而其余的文件能够选择。
由于选择文件的时候是用的 (change)事件,因此在删除以后不能选择相同的文件。dom
个人方法是,删除以后清除掉上传的 input dom,而后再建立这个 dom。
模板中:
input 元素添加 *ngIf = "isShowSelectFile"
组件中:
初始化时,isShowSelectFile: boolean = true;
删除时:this
this.isShowSelectFile = false; setTimeout(() => { this.isShowSelectFile = true; }, 100);
这里附上关键代码,查看codepen在线示例关键代码(ng2-file-upload 插件在 Angular 中怎么使用请参考Angular2使用ng2-file-upload上传文件 ):spa
<div class="upload-template"> <strong>上传模板:</strong> <div class="upload-file-container"> <span class="upload-name" [class.uploaded-template]="selectedFileName !== '选择文件'">{{selectedFileName}}</span> <input id="selectFile" type="file" *ngIf="isShowSelectFile" placeholder="选择填写好的数据文件" title="选择填写好的数据文件" ng2FileSelect [uploader]="uploader" [disabled]="isImportingData" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" (change)="selectedFileOnChanged($event)"> </div> <!--若文件已上传--> <button [hidden]="selectedFileName == '选择文件'" type="button" class="delete" title="删除" (click)="deleteUploadedFile()">删除</button> </div>
// 删除上传的文件 deleteUploadedFile() { this.selectedFileName = "选择文件"; this.uploader.clearQueue(); this.uploadEnabled = false; this.isShowSelectFile = false; setTimeout(() => { this.isShowSelectFile = true; }, 100); } selectedFileOnChanged(event:any) { let filePath = event.target.files[0].name; //用户取消选择文件 if(event.target.value =="") { this.uploader.clearQueue(); this.selectedFileName = "选择文件"; this.uploadEnabled = false; } else { //每次选择后,都只保留最新选择的文件 let fileCount = this.uploader.queue.length; if(fileCount > 1) { for(let i = 1; i < fileCount; i++) { this.uploader.removeFromQueue(this.uploader.queue[0]) } } } this.uploadEnabled = this.uploader.queue.length > 0; }
SCSS: .upload-template { $size: 36px; .upload-file-container { position: relative; height: $size; line-height: $size; cursor: pointer; margin-left: 10px; .upload-name { z-index: 2; width: 100%; position: absolute; top: 0; bottom: 0; right: 0; left: 0; display: block; text-decoration: underline; height: $size; line-height: $size; color: #29e; overflow-x: hidden; text-overflow: ellipsis; white-space: nowrap; &.uploaded-template { color: #444; text-decoration: none; } & + input { z-index: 3; width: 100%; position: absolute; top: 0; bottom: 0; right: 0; left: 0; display: block; height: $size; line-height: $size; opacity: 0; } } } .delete { float: left; color: #f00; line-height: $size; padding-right: 1em; padding-left: 1em; } }
在 firefox 浏览器中,当未选择文件时,美化后样式是:
当已选择文件时,美化后样式是:
firefox