上傳進度條功能示例
阿新 • • 發佈:2020-11-29
一、簡介
本文例項主要講述了ng-cli 與JS+html5實現非同步檔案上傳進度條顯示功能
二、ng-cli版本
使用了angular-cli、NG-ZORRO中的nz-upload
1)http.service.ts:
2)xxx.html:
<div class="upFiles">
<div class="spangrup">上傳配置檔案</div>
<div>
<nz-upload style="display: inline-block" nzType="drag" nzAction='{{fileUrlSite}}' [nzCustomRequest]="customReq">
<p class="ant-upload-drag-icon">
<i nz-icon nzType="upload"></i>
</p>
<p class="ant-upload-text">點選或將檔案拖拽到這裡上傳</p>
</nz-upload>
</div>
</div>
3)xxx.ts:
/**
* 上傳檔案模組
*/
import { HttpClient, HttpEvent, HttpEventType, HttpRequest, HttpResponse } from '@angular/common/http'; //需引入
customReq = (item: UploadXHRArgs) => {
const formData = new FormData();
formData.append('file', item.file as any);
const req = new HttpRequest('POST', item.action!, formData, {
reportProgress: true
});
return this.http.request(req).subscribe(
(event: HttpEvent<any>) => {
if (event.type === HttpEventType.UploadProgress) {
//console.log(event.total!);
if (event.total! > 0) {
(event as any).percent = (event.loaded / event.total!) * 100;
}
item.onProgress!(event, item.file!);
} else if (event instanceof HttpResponse) {
//console.log(event);
if (event.body.code !== 200) {
item.onError!('', item.file!);
this.message.error(event.body.msg);
} else {
item.onSuccess!(event.body, item.file!, event);
this.message.success('上傳成功');
}
}
},
err => {
//console.log(err);
item.onError!(err, item.file!);
}
);
}
4)頁面展示:
三、JS+html5版本
1)html:
2)js:
<script type="text/javascript">
let xhr;
let ot;//
let oloaded;
//上傳檔案方法
function UpladFile() {
let fileObj = document.getElementById("file").files[0]; // js 獲取檔案物件
let url = "http://192.168.108.24:30573/xxx/xxx/"; // 接收上傳檔案的後臺地址
let form = new FormData(); // FormData 物件
form.append("mf", fileObj); // 檔案物件
xhr = new XMLHttpRequest(); // XMLHttpRequest 物件