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