from;https://github.com/think2011/localResizeIMG
lrz.js
npm install lrz
//上传文件
PostFile: function (url, formData) {
var instance = axios.create({
timeout: "10000",
headers: {
"userid": getCookie("userId"),
"corpid": getCookie("corpId"),
"Content-Type": "multipart/form-data"
}
});
instance.interceptors.response.use(function (response) {
console.log(JSON.stringify(response.data), response.headers.errcode)
if (JSON.stringify(response.headers) == "{}") {
vueObj.$children[0].showToast({ message: "上传失败,文件超过6M或网速较慢", timeout: 2000 });
return Promise.reject(response);
} else {
return response;
}
}, function (error) {
if (error.response.status == 429 ) {//超时
vueObj.$children[0].showToast({ message: "系统繁忙,请稍后再试!", timeout: 2000 });
}
if (error.code == "ECONNABORTED" || error.message.indexOf(‘timeout‘) > -1 || error.message == ‘Network Error‘ ) {//超时
vueObj.$children[0].showToast({ message: "请求数据超时,请稍后再试!", timeout: 2000 });
}
if (error.response && error.response.status == 500) {
if (error.response.headers.errcode > 1000 || [‘107‘, ‘109‘, ‘101‘, ‘102‘, ‘108‘, ‘103‘, ‘105‘].indexOf(error.response.headers.errcode) != -1) {
vueObj.$children[0].showToast({ message: decodeURIComponent(error.response.headers.errmsg).replace(new RegExp("\\+", "g"), " "), timeout: 2000 });
}
}
return Promise.reject(error);
});
console.log(1111)
console.log(formData.get("file"))
return lrz(formData.get("file"), {
quality: 0.7 //自定义使用压缩方式
})
.then(function(rst) {
console.log(rst)
console.log(222)
var file = new File([rst.file], rst.origin.name, {type: rst.origin.type});
formData.set("file",file);
return instance.post(url, formData);
})
.catch(function(error) {
//失败时执行
return Promise.reject(error);
})
.always(function() {
//不管成功或失败,都会执行
});
//return instance.post(url, formData);
},
原文:https://www.cnblogs.com/liuqiyun/p/13156996.html