import { api_uploadAttachment } from "@/http/api.js" export function useUploadFile() { /** * 压缩 */ const toBlob = (canvas, imgObj) => { return new Promise((resolve,reject) => { canvas.toBlob((fileSrc) => { resolve(fileSrc) }, `${imgObj.fileType}/${imgObj.extname}`, 0.3) }) } /** * 图片加载完成 */ const newImage = (img) => { return new Promise((resolve,reject) => { img.onload = () => { resolve() } }) } /** * 上传图片 */ const uploadFile = async (imgObj, type, incidentId) => { const res = await uni.getImageInfo({src: imgObj.url}); console.log('压缩前', res) let canvasWidth = res.width //图片原始长宽 let canvasHeight = res.height let img = new Image() img.src = res.path let canvas = document.createElement('canvas'); let ctx = canvas.getContext('2d') canvas.width = canvasWidth canvas.height = canvasHeight await newImage(img) ctx.drawImage(img, 0, 0, canvasWidth, canvasHeight) const fileSrc = await toBlob(canvas, imgObj) let tp = window.URL.createObjectURL(fileSrc) console.log('压缩后', tp); return uni.uploadFile({ url: api_uploadAttachment(type, incidentId), filePath: tp, name: 'file', formData: { 'filename': imgObj.name } }); } return { uploadFile }; }