结合文章 - 阿里OSS Java-SDK带进度条上传,配合前端element-ui upload组件使用示例
表单中的 ui
<el-form-item label="课程文件" :label-width="formLabelWidth">
<el-upload
:show-file-list="false"
:file-list="playUrls"
:http-request="uploadSectionFile"> <!--此处使用自定义上传实现http-request-->
<el-button size="small" type="primary">点击上传</el-button>
<el-tag v-show="showSectionFileName" type="gray">{{sectionFileName}}</el-tag>
<div slot="tip" class="el-upload__tip">请等待进度条100%之后再提交表单</div>
</el-upload>
<el-progress v-show="showProgress" :text-inside="true" :stroke-width="18"
:percentage="uploadPercent"></el-progress>
</el-form-item>
http-request
指向的函数会有一个element 的默认回调参数
定义为param.里面包含很多东西,可以自己debug查看
param.file
就是要上传的文件
uploadSectionFile: function (param) { //自定义文件上传
var fileObj = param.file;
// 接收上传文件的后台地址
var FileController = "/file/item/upload";
// FormData 对象
var form = new FormData();
// 文件对象
form.append("file", fileObj);
// 其他参数
form.append("xxx", xxx);
// XMLHttpRequest 对象
var xhr = new XMLHttpRequest();
xhr.open("post", FileController, true);
xhr.upload.addEventListener("progress", vm.progressFunction, false); //监听上传进度
xhr.onload = function () {
vm.Form.playUrl = xhr.response; //接收上传到阿里云的文件地址
vm.$message({
message: '恭喜你,上传成功!',
type: 'success'
});
};
xhr.send(form);
},
监听上传进度中指定的函数,此函数在上传过程中会一直执行,所以通过
i
来控制只执行一次
progressFunction: function () {
if (vm.i == 0) { //控制上传中状态只执行一次上传
vm.showStatus();
vm.showProgress = true;
vm.i = 1;
}
},
定时查询上传进度
uploadPercent
是上传进度
showStatus: function () {
var intervalId = setInterval(function () {
$.get("/file/item/percent", {}, function (data) {
var percent = data;
if (percent >= 100) {
clearInterval(intervalId);
percent = 100;//不能大于100
vm.uploadPercent = percent;
vm.resetPercent(); //在文章开头的上篇文章中有此函数,用于重置后台的上传进度
}
vm.uploadPercent = percent;
}, "json");
}, 1000);
},