概述:
上传控件模板:
<input type="file" @change="getFileInfo($event)">
input
组件选择文件后可以获取到文件信息,然后开始上传
设定每次分片的大小 sizes
,总片数 = 文件大小 / 分片大小
记录当前片数,开始循环总片数,给所有分片加密。
加密的逻辑是:
用 File
实例对象上的 slice
方法把拿到的文件进行分片,然后用 FileReader
对象读取分片后的每一片文件内容,监听 onload
事件,读取完成后将结果用 md5
算法加密。
加密完成后调用后端接口去检查当前文件是否上传过(用 md5
值判断),上传到第几片了:
如果已经传过,就直接返回文件地址,实现秒传;
如果没有传过,当前片数为 0
,开始上传;
如果传过一部分,就返回当前片数,从当前片数开始上传,实现断点续传。
代码:
<script>
import SparkMD5 from 'spark-md5';
import {url} from '~/config';
/** 单文件上传
* uploadResult(data) 上传结果
* uploadError(err) 上传错误
* md5Progress(err) md5 加密进度
* checkFileMd5Error(err) md5核对错误
* uploadProgress(data) 上传进度
* uploadFileInfo 文件信息
*/
let upload = `${url.hpath}/image/index`;
//支持 秒传, 断点,分片上传
export default {
props: {
// 自定义滚动条 默认使用
customProgress: {
default: true,
type: Boolean
},
// 是否展示md5的核验进度,不显示进度,就显示文案: 文件核验中, 默认显示
isShowMd5Progress: {
default: true,
type: Boolean
},
// 文件大小限制, MB
limitSize: {
default: -1,
type: Number,
},
// 上传类型限制, 默认没有限制, 接受类型 `zip,png`
limitType: {
default: 'any',
type: String
},
// 文件上传要求
tips: {
default: '',
type: String
}
},
data() {
return {
file: null,
md5: '',
sizes: 2 * 1024 * 1024, // 每次分片的大小
isPause: false,
// md5进度条信息
md5ProgressInfo: {
chunk: 0,
chunks: 0
},
// 上传进度条
uploadProgressInfo: {
chunk: 0,
chunks: 0
},
// 是否开始上传
isStart: false,
isMiaoc: false,
}
},
computed: {
md5Percentage() {
let proInfo = this.md5ProgressInfo;
if (proInfo.chunks > 0) {
let percentage = (proInfo.chunk / proInfo.chunks).toFixed(2) * 100;
return Math.floor(percentage);
}
return 0;
},
uploadPercentage() {
let proInfo = this.uploadProgressInfo;
if (proInfo.chunks > 0) {
let percentage = (proInfo.chunk / proInfo.chunks).toFixed(2) * 100;
return Math.floor(percentage);
}
return 0;
}
},
methods: {
// 文案显示
formatMd5(percentage) {
return percentage === 100 ? '核验完成' : `md5核验中:${percentage}%`;
},
formatUpload(percentage) {
return percentage === 100 ? '上传完成' : `文件上传中:${percentage}%`;
},
// 获取信息
getFileInfo(e) {
this.file = e.target.files[0];
this.$refs.filed.value = null;
this.isStart = false;
this.isMiaoc = false;
this.$emit('uploadFileInfo', this.file)
// console.log(this.file);
this.startUpload();
},
pauseUpload() {
this.isPause = true;
},
continueUPload() {
this.isPause = false;
this.uploadFile(this.markInfo.index, this.markInfo.chunks);
},
// 开始上传
startUpload() {
if (!this.file) {
this.$message.error('请选择文件');
return;
}
if (this.limitSize != -1 && (this.file.size / 1024 / 1024) >= this.limitSize) {
this.$message({
message: `请将文件控制在${this.limitSize}M范围内`,
type: 'warning'
});
return false;
}
if (this.limitType != 'any') {
let limitList = this.limitType.split(',');
for (let item of limitList) {
if (this.file.name.indexOf(item) > -1) {
break;
} else {
this.$message({
message: `请上传正确的格式`,
type: 'warning'
});
return;
}
}
}
// if(this.file.name.indexOf('zip') < 0) {
// this.$message.warning('上传文件只能是.zip格式的压缩文件。');
// return false;
// }
this.isStart = true;
/**
* md5 分片后的md5 值
* chunks 总共的分片数
*/
this.setSparkMD5(this.file, (e, md5, chunks) => {
this.md5 = md5;
this.$axios.post(`${upload}/checkAndAnalyze`, {
md5: md5,
size: this.file.size,
chunks: chunks,
name: this.file.name,
}, {progress: false})
.then((res) => {
let {code, data, msg} = res.data
if (code === 1000) {
// 100文件已经存在, 101-文件不存在,102-已有部分文件
if (data.uploadCode === 100) {
this.isMiaoc = true;
this.$emit('uploadResult', data.uploadPath);
} else if (data.uploadCode === 101) {
this.uploadFile(0, chunks)
} else {
this.uploadFile(data.lastChunk, chunks)
}
} else {
this.$emit('checkFileMd5Error', msg)
}
})
.catch((err) => {
this.$emit('checkFileMd5Error', 'md5校验异常')
})
})
},
/**
* index 当前的片数, 默认0开始(或者服务端返回的片数)
* chunks 总片数
*/
uploadFile(index, chunks) {
let self = this;
let file = this.file;
if (this.isPause) {
this.markInfo = {
index,
chunks,
}
return;
}
if (index < chunks) {
let shardSize = self.sizes; // 每次上传的大小
let totalSize = file.size; // 文件的总大小
//计算每一片的起始与结束位置
let start = index * shardSize; // 上传的开始字节
// let end = start + shardSize; // 结束字节
var end = Math.min(file.size, start + shardSize);
// 生成 Md5 , 将文件切割后 , 将 切割后的 文件 读入内存中
let singleFile = file.slice(start, end); //截取每次需要上传字节数
let formData = new FormData();
formData.append('md5', this.md5);
formData.append('chunkSize', this.sizes);
formData.append('name', this.file.name);
formData.append('type', this.file.type);
formData.append('lastModifiedDate', this.file.lastModifiedDate);
formData.append('size', this.file.size);
formData.append('chunks', chunks);
formData.append('chunk', index);
formData.append('file', singleFile);
this.$axios.post(`${upload}/upload`, formData, {progress: false})
.then((res) => {
index ++;
this.uploadProgressInfo = {
chunk: index,
chunks
}
this.$emit('uploadProgress', this.uploadProgressInfo);
this.uploadFile(index, chunks)
})
.catch((err) => {
this.$emit('uploadError', '上传服务异常')
})
} else {
this.startUpload();
}
},
// 文件上传完成后,掉用一个回调函数 得到md5值
setSparkMD5(file, callback) {
let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
chunkSize = this.sizes,
chunks = Math.ceil(file.size / chunkSize),
currentChunk = 0,
spark = new SparkMD5.ArrayBuffer(),
fileReader = new FileReader();
let _this = this;
fileReader.onload = function (e) {
// console.log('read chunk nr', currentChunk + 1, 'of', chunks);
spark.append(e.target.result); // Append array buffer
currentChunk++;
_this.md5ProgressInfo = {
chunk: currentChunk,
chunks
}
_this.$emit('md5Progress', _this.md5ProgressInfo)
if (currentChunk < chunks) {
loadNext();
} else {
callback(null, spark.end(), chunks);
// console.log(spark.end(), 'end')
// console.log('finished loading');
}
};
fileReader.onerror = function () {
callback('oops, something went wrong.');
};
function loadNext() {
var start = currentChunk * chunkSize,
end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
}
console.log(spark.end(), 'end')
loadNext();
},
}
}
</script>
模板:
<div class="md5-upload">
<div class="first-step">
<div class="upload-demos">
<img src="~/assets/img/competitionnew/ic-upload.png" alt="">
<input type="file" class="uploadfile" ref="filed" @change="getFileInfo($event)">
</div>
<span class="tip">文件格式</span>
<span class="tip-detail">{{tips}}</span>
<div class="file-list">
<p v-if="file" class="file-name">{{file.name}}</p>
<template v-if="customProgress">
<div v-show="isStart" class="upload-progress">
<el-progress :percentage="100" :text-inside="true" :stroke-width="20" :format="formatUpload" v-if="isMiaoc"></el-progress>
<template v-else>
<template v-if="md5Percentage < 100">
<el-progress :percentage="md5Percentage" :text-inside="true" :stroke-width="20" :format="formatMd5" v-if="isShowMd5Progress"></el-progress>
<p>文件核验中</p>
</template>
<el-progress :percentage="uploadPercentage" :text-inside="true" :stroke-width="20" :format="formatUpload" v-if="md5Percentage >= 100"></el-progress>
</template>
</div>
</template>
</div>
</div>
</div>