1、jq实现
let time = parseInt(new Date().getTime()/1000) + '' + parseInt(Math.random() * 1000); // 文件名
function upload (file, num) {
let formData = new FormData();
let chunkTotal = Math.ceil(file.size / _this.chunkSize); // 总的chunk数
let nextSize = Math.min((num + 1) * _this.chunkSize, file.size);
let fileData = file.slice(num * _this.chunkSize, nextSize);
formData.append("file", fileData);
formData.append("name", time);
formData.append("chunk", num);
formData.append("chunks", chunkTotal);
$.ajax({
url: "http://xxx.xxx.com/xxx/bigFile/upload",
type: "POST",
data: formData,
xhrFields: {
withCredentials: true // 这里设置了withCredentials
},
processData: false,
contentType: false,
success: function (body) {
if (body.code === 0) {
if (num < chunkTotal - 1) {
upload(file, num + 1); //递归调用
}
} else {
alert(body.msg)
}
}
});
}
upload(file, 0);
2、axios实现
import axios from 'axios';
let time = parseInt(new Date().getTime()/1000) + '' + parseInt(Math.random() * 1000); // 文件名
function upload (file, num) {
let formData = new FormData();
let chunkTotal = Math.ceil(file.size / _this.chunkSize); // 总的chunk数
let nextSize = Math.min((num + 1) * _this.chunkSize, file.size);
let fileData = file.slice(num * _this.chunkSize, nextSize);
formData.append("file", fileData);
formData.append("name", time);
formData.append("chunk", num);
formData.append("chunks", chunkTotal);
let config = {
headers: {
'Content-Type': 'multipart/form-data'
}
}
axios.post('http://xxx.xxx.com/xxx/bigFile/upload', formData, config).then(res => {
if (res.data && res.data.code === 0) {
if (num < chunkTotal - 1) {
upload(file, num + 1); //递归调用
}
} else {
alert(res.data.msg)
}
}, err => {
alert('请求出错')
})
}
upload(file, 0);