場景:上傳檔案,上傳后還可點擊編輯彈出模態框重新上傳,使用ng-zorro-antd庫開發,運用nz-upload組件的[nzCustomRequest]自定義上傳,
Bug:[nzCustomRequest]自定義上傳介面調通后大概是由于介面回傳的資料和組件封裝所需的資料格式不符的原因導致:**上傳的檔案串列的status始終處于loading狀態,并且上傳進度始終為0,**如下圖:

最初解決方案,為所欲為的瞎用(不推薦):
1)解決一直loading的思路來源于檔案的中的(nzChange),因為他的回呼中包含status欄位,如下圖:

通過nz-upload組件系結(nzChange)事件,方法中強行修改檔案見串列的status值,代碼如下:
fileChage(file){
file.file.status='done'; // 改變檔案串列中檔案的狀態,強行阻止一直loading的問題
}
2)進度條始終為0的問題,也是看到官方檔案有相應的方法,才瞎搞的,如下圖:

代碼如下:
// 上傳
firmwareFileCustomRequest = (file: any) => {
const fd = new FormData();
fd.append("file", file.file as any);
this.equiment.postFirmwareUpload(fd).subscribe(
(event: HttpEvent<{}>) => {
(event as any).percent = 100; // 進度條的值直接設定為100
// tslint:disable-next-line:no-non-null-assertion
file.onProgress!(event, file.file!); // 進度事件回呼
// 可以解決問題,但不推薦,
},
err => {
// tslint:disable-next-line:no-non-null-assertion
file.onError!(err, file.file!);
}
);
}
最終解決方案(推薦):
通過[nzBeforeUpload]給檔案串列賦值,然后自定義上傳[nzCustomRequest]中正常上傳即可,
完整代碼如下:
<nz-upload id='firmwareFile' [nzCustomRequest]="firmwareFileCustomRequest" [nzFileList]='firmwareFileList'
[nzBeforeUpload]="beforeUpload" nzAccept=".crt" [nzRemove]="firmwareFileRemove">
<button nz-button><i nz-icon nzType="upload"></i>{{'app.equipment.SelectFirmware' | translate}}</button>
</nz-upload>
import { NzUploadFile} from 'ng-zorro-antd/upload';
import { HttpEvent } from '@angular/common/http';
export class TboxManagerComponent implements OnInit {
// ....
firmwareFileList: NzUploadFile[] = []; // 上傳檔案串列
// ....
// ....
beforeUpload = (file: NzUploadFile): any => {
this.firmwareFileList = this.firmwareFileList.concat(file);
// return false;
}
// 上傳
firmwareFileCustomRequest = (file: any) => {
const fd = new FormData();
fd.append("file", file.file as any);
this.equiment.postFirmwareUpload(fd).subscribe(
(event: HttpEvent<{}>) => {
// ...
// 成功后的一些邏輯操作操作
// ...
},
err => {
// tslint:disable-next-line:no-non-null-assertion
file.onError!(err, file.file!);
}
);
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/212432.html
標籤:其他
