html代码片段
<div>
<input type="file" ref="fileInput" @change="uploadfile" style="display:none" id="uploader" />
<label class="label-uploader" for="uploader" v-if="fileData.length<9"> <img src="../../images/interactiveModule/uploadImg.png"/> </label>
</div>
data里面定义数据
return{
uploadFlag:true,
isShowVideo:true,
fileData:[],
fileDataStr:'',
bytesPerPiece:5 * 1024 * 1024,//分片大小
videoSlicingData: [],
videoUrl:'',
}
}
methods方法
uploadfile(event) {
if (!this.uploadFlag) {
alertMsg('正在上传,请稍等');
return false;
}
let file = event.target.files;//获取本地视频
if (file[0].size > 0) {
this.uploadFlag = false;
}
if (/(video)/i.test(file[0].type)) {
this.videoSlicing(file[0]);
} else if (/image/.test(file[0].type)) {
this.uploadImg(file[0]);
}else{
alertMsg('上传文件类型为视频或图片');
this.uploadFlag = true;
}
},
对视频进行分片
videoSlicing(file, id) {
let that = this;
let start = 0;
let end;
let index = 0;
let filesize = file.size;
let filename = file.name;
let time = parseInt(new Date().getTime() / 1000);
that.videoSlicingData = [];
//计算文件切片总数
while (start < filesize) {
end = start + that.bytesPerPiece;
if (end > filesize) {
end = filesize;
}
let chunk = file.slice(start, end);//切割文件
that.videoSlicingData.push({
'file': chunk,
'filename': filename,
'time': time,
'index': index,
'flag': false,
'isUpload': true,
})
that.uploadVideo(chunk, filename, time, index, id);
start = end;
index++;
}
},
视频上传
uploadVideo(file, filename, sourceid, index, id) {
let formData = new FormData();
let that = this;
formData.append("file", file, filename);
$.ajax({
url: url,//分片上传的接口
data: formData,
type: 'post',
dataType: "json",
cache: false,
processData: false,
contentType: false,
success: function (data) {
if (data.status == 201) {
that.videoSlicingData[index].flag = true;
that.videoSlicingData[index].isUpload = false;
let allOk = 0;
that.videoSlicingData.map(function (val, _index) {
if (!val.flag && !val.isUpload) {
that.uploadVideo(val.file, val.filename, val.sourceid, val.index, id);
} else if (val.flag) {
allOk += 1;
}
})
if (allOk == that.videoSlicingData.length) {
that.getVideoSrc(sourceid, filename, that.videoSlicingData.length, id);
}
} else {
alertMsg(data.message);
}
},
error: function () {
alertMsg('请稍后再试');
that.uploadFlag = true;
}
})
},
上传成功之后,最后一个分片调用整体接口
getVideoSrc(sourceid, name, sum, id) {
let that = this;
$.ajax({
url: url,//接口地址
type: 'post',
dataType: "json",
data: {
'sourceid': sourceid,
'complete': 1,
'number': sum,
'name': name
},
success: function (data) {
if (data.status == 200) {
that.fileData.push({'url':data.result,'type':'video'})
that.fileDataStr+=data.result+','
$("#uploader").val('')
} else {
alertMsg(data.message);
$("#uploader").val('')
}
that.uploadFlag = true;
},
error: function () {
alertMsg('请稍后再试');
that.uploadFlag = true;
}
})
},