<template>
<view class="content">
<view @click="change">分片上传</view>
<view>上传进度{{percent}}%</view>
<view v-if="fileurl">{{fileurl}}</view>
</view>
</template>
<script>
export default {
data() {
return {
fileurl: '',
bytesPerPiece: 1024 * 1024 * 1, // 每个文件切片大小定为1MB .
percent: 0,
uploadSize: 0
}
},
onLoad() {
},
methods: {
async change() {
uni.chooseFile({
count: 6, //默认100
extension:['.zip','.rar'],
success: async (res) => {
this.uploadSize = 0;
let tempFiles = res.tempFiles[0];
let chunkid = this.guid();
let bytesPerPiece = this.bytesPerPiece;
let totalPieces = 0;
let blob = tempFiles;
let start = 0;
let end;
let index = 0;
let filesize = blob.size;
let filename = blob.name;
//计算文件切片总数
totalPieces = Math.ceil(filesize / bytesPerPiece);
while(start < filesize) {
if(index >= totalPieces) {
break;
}
end = start + bytesPerPiece;
if(end > filesize) {
end = filesize;
}
let chunk = blob.slice(start,end);//切割文件
let sliceIndex= blob.name + index;
let formData = {
'chunkid': chunkid, // 切片文件唯一标识id
'chunkindex': index, // 当前切片索引
'chunkcount': totalPieces, // 切片总数
'filename': filename, // 切片文件名
}
await this.addFile(chunk, formData, filesize).then(res => {
console.log(res)
this.uploadSize += chunk.size;
if(index+1 == totalPieces && res.filepath) {
this.fileurl = res.filepath;
this.percent = 100;
}
start = end;
index++;
});
}
}
});
},
addFile(chunk, formData, filesize){
return new Promise(resolve => {
var uploadTask = uni.uploadFile({
url: 'http://tp6.cs2.com/index/upload', //仅为示例,非真实的接口地址
file: chunk,
formData: formData,
name: 'file',
success: (uploadFileRes) => {
resolve(JSON.parse(uploadFileRes.data))
}
});
uploadTask.onProgressUpdate((res) => {
// console.log('上传进度' + res.progress);
// console.log('已经上传的数据长度' + res.totalBytesSent);
// console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
let total = 0
if (formData.chunkindex > 0) {
total = this.uploadSize + res.totalBytesSent
} else {
total = res.totalBytesSent
}
let percent = Math.round(
(total / filesize) * 100
);
if (this.percent < percent) {
this.percent = percent > 100 ? 100 : percent;
}
});
});
},
guid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0,
v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
}
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.logo {
height: 200rpx;
width: 200rpx;
margin-top: 200rpx;
margin-left: auto;
margin-right: auto;
margin-bottom: 50rpx;
}
.text-area {
display: flex;
justify-content: center;
}
.title {
font-size: 36rpx;
color: #8f8f94;
}
</style>
08-02
1万+
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-05
1195
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
10-20