处理流程
canvas->base64->file->formData->设置请求头'multipart/form-data'->服务器KoaBody设置multipart: true->上下文获取文件路径->图片上传
前端
html2canvas(canvasEle, {
width: canvasEle.offsetWidth, //设置canvas的宽度
scale: 4, //缩放
useCORS: true,
height: canvasEle.offsetHeight, //设置截图的长度
}).then(canvas => {
//处理生成的canvas
const file = base64ToFile(canvas.toDataURL())
const formData = new FormData()
formData.append('tabImg', file, 'table.png')
uploadImg(formData, {
headers: {
'Content-Type': 'multipart/form-data',
transformRequest: [data => data],
},
}).then(res => {
console.log(
'%c [ 图片上传 ]-55',
'font-size:13px; background:pink; color:#bf2c9f;',
res,
)
})
})
// base64ToFile处理代码
function dataURLtoBlob(dataurl) {
let arr = dataurl.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = window.atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
return new Blob([u8arr], {
type: mime,
})
}
function blobToFile(theBlob, fileName) {
theBlob.lastModifiedDate = new Date()
theBlob.name = fileName
return theBlob
}
export function base64ToFile(dataurl) {
const blob = dataURLtoBlob(dataurl)
return blobToFile(blob, 'tableImg')
}
后端
const app = new Koa()
app.use(koaBody({multipart: true, jsonLimit: '50mb' }));
export const uploadImg = post('/report/upload')(async (ctx)=>{
try {
const files = ctx.request.files;
const client = new File({
bucket: 'refactor',
});
const res = await client.upload(files.tabImg.path,{
filename: moment().format('YYYY-MM-DD')
})
ctx.body = {
code: 0,
msg: 'ok',
data: res.data.originalLink
}
} catch (error) {
ctx.body = {
code: 1,
msg: 'error',
}
}
})