将canvas转化为图片并上传服务器,有两种思路
思路1 直接将canvas转化为base64编码,将base64编码的字符串上传服务器,让后端转化为图片;
思路2 需要将canvas的内容先转化为base64编码的字符串,再将字符串转化为file上传;
canvas转化为64
canvasToBase64: function(canvas){
// 'image/png'可以换成'image/jpeg'
return canvas.toDataURL('image/png');
}
canvas转化为图片
canvasToImg: function(canvas){
let image = new Image();
image.src = canvas.toDataURL('image/png')
return image;
}
base64转化为file
base64ToFile: function(urlData, fileName){
let arr = urlData.split(',');
let mime = arr[0].match(/:(.*?);/)[1];
let bytes = atob(arr[1]);
let n = bytes.length
let ia = new Uint8Array(n);
while (n--) {
ia[n] = bytes.charCodeAt(n);
}
return new File([ia], fileName, { type: mime });
}
使用formData上传canvas
submitImg: function(canvas){
let param= new FormData();
param.append("file", this.base64ToFile(canvas.toDataURL('image/png'));
param.append("user_name", 'mason');
// 注意添加headers
axios.post('/que/admin/final/report/chess/image/add/', param, {headers:{'Content-Type': 'multipart/form-data'}}).then(res=>{
console.log(res.data);
});
}