oss 分片上传 动态条实现
1111
1
0
1年前
本片讲述了使用angular和springboot实现上传进度条的展示
server端上传代码,你可以使用自己定义的
本人使用的是oss的分片上传--------接口文档:https://help.aliyun.com/document_detail/84786.html?spm=a2c4g.11186623.6.722.52711bd4xfDASh
oss进度条接口文档:https://help.aliyun.com/document_detail/84796.html?spm=a2c4g.11186623.6.723.1d0c4d836wnzjv
进度条的实现是需要实现ProgressListener并且根据自己的业务需要重写
```
@Override
public void progressChanged(ProgressEvent progressEvent) {}
```
web端
1.安装ng2-file-upload
命令:npm install ng2-file-upload --save
2.声明组件
```
@NgModule({
declarations: [
],
imports: [
FileUploadModule,
],
providers: [
],
bootstrap: [],
})
export class Module {
}
```
3.angular ts文件中实现
a. 初始化uploader
```
private uploader: FileUploader = new FileUploader({
url: 你要上传的URL,
method: 'POST',
itemAlias: 'file',
<!--解决302重定向问题-->
headers: [{name: "X-Requested-With", value: ""}],
});
```
b.实现上传函数
```
<!--用来在上传前做一些验证处理-->
selectedFileOnChanged(event: any) {
console.info("event"+event);
}
selectFile() {
document.getElementById("file").click();
}
uploadFile() {
// 上传
let myself = this;
this.uploader.queue[0].onSuccess = function (response, status, headers) {
let res = JSON.parse(response);
let url = res.result;
if (status == 200) {
}
};
this.uploader.queue[0].upload(); // 开始上传
let pro = null;
let self = this;
<!--setInterval详解:http://www.runoob.com/jsref/met-win-setinterval.html-->
pro = setInterval(async function () {
<!--调用你监控的方法,实时返回上传进度-->
self.progressBar = await self.apkService.progress();
<!--根据业务需要渲染页面-->
let total = self.progressBar.total;
let currentPart = self.progressBar.currentPart;
let percent = currentPart / total;
if (total == currentPart) {
<!--上传完成终止调用-->
clearInterval(pro);
$('#progress').progress({
percent: 100
});
} else {//正在上传
$('#progress').progress({
percent: percent * 100
});
}, 2000);
}
```
c.html
```
<div class="inline fields">
<label class="input-label">上传安装包:</label>
<input type="text" [value]="selectFileName" class="form-control"
readonly="true" style="width: 55rem;"/>
<input type="file" ng2FileSelect [uploader]="uploader"
(change)="selectedFileOnChanged($event)"
id="file" accept=".apk"/>
<input class="btn btn-default" type="button" value="浏览..."
(click)="selectFile()" style="margin-left: 0.5rem;"/>
<input class="btn btn-primary" type="button" value="上传"
(click)="uploadFile($event)" style="margin-left: 0.5rem;"/>
</div>
<div class="ui progress" id="progress">
<div class="bar">
<div class="progress"></div>
</div>
<div class="label">上传文件</div>
</div>
```
注意:本人使用的ui框架为semantic,如果样式实现有问题请自己调整
大神详解:https://www.cnblogs.com/javayuan/p/5391336.html
总结:进度条实现的难点在于实时返回上传进度,这时就需要server端做个对上传进度的监控,并根据自己的业务逻辑向前台返回实时上传数据
web端实现定时调用server端生成的数据然后渲染HTML实现进度条