vue,
原理:
1.读取图片文件为base64格式
2.使用canvas压缩分辨率,(图片会变小)
3.canvas转成blob,(ios上不要专程file,file可能有信息,但是没有数据)
代码:
compress:function(img, width, height, ratio) {
var canvas, ctx, img64;
canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
img64 = canvas.toDataURL("image/jpeg", ratio);
return img64;
},
doCompressTheChoosedImg:function(){
var image = document.getElementById('choosedImage')
var base64=this.compress(image, image.width,
image.height, 0.5)
var blob=this.dataURLtoBlob(base64, 'image/jpeg')
var file=new File([blob], 'onsite-work.jpg', {type:'image/jpeg',
lastModified:Date.now()})
//返回blob,因为ios上生成图片文件的时候有文件信息,却没有文件内容
//Content-Disposition: form-data; name="file"; filename="onsite-work.jpg"
//Content-Type: image/jpeg
//
//
//------WebKitFormBoundaryb20QDAWYwA2MB9CA--
//所以直接返回blob了
return blob
},
dataURLtoBlob:function (dataURI,type) {
var binary = atob(dataURI.split(',')[1]);
var array = [];
for(var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
var blob = new Blob([new Uint8Array(array)], {type:type});
return blob
},
调用:
upload:function(){
if (this.$refs.newImage.files.length < 1){
this.tips = '请先选择图片'
this.dialogVisible = true
return
}
//此处执行压缩图片,input标签的id设为newImage,
var file=this.doCompressTheChoosedImg(this.$refs.newImage.files[0])
var formData = new FormData();
formData.append('file', file)
let config = {headers:{'Content-Type':'multipart/form-data'}}
this.loading = true
this.axios.post('/upload/uploadImage',
formData, config
).then(res=>{
if (0 == res.data.statusCode){
this.tips = '上传成功'
this.dialogVisible = true
}else{
this.loading = false
this.tips = '上传失败,错误码:' + res.data.statusCode
this.dialogVisible = true
}
}).catch(error=>{
this.loading = false
})
},
调试过程:
1.不压缩图片直接上传没有问题
2.压缩图片上传,pc端浏览器没有问题,android也没有问题,ios报错
3.fiddle查看ios请求数据
------WebKitFormBoundaryb20QDAWYwA2MB9CA
Content-Disposition: form-data; name="file"; filename="onsite-work.jpg"
Content-Type: image/jpeg
------WebKitFormBoundaryb20QDAWYwA2MB9CA--
对比成功的请求,可以看出file有基础信息,但是没有没有数据
4.反正web请求要的是文件数据,不是文件。所以干脆把blob直接返回,不生成文件了,android、ios测试通过