一、简介
本文实例主要讲述了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 对象