import { api_uploadAttachment } from "@/http/http.js" import Compressor from 'compressorjs'; /** * 压缩 */ 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 compressImage = (file) => { return new Promise((resolve,reject) => { new Compressor(file, { quality: 0.6, // 压缩质量,范围从0到1 maxWidth: 1500, // 最大宽度 maxHeight: 1500, // 最大高度 success: (result) => { resolve(result); // 压缩后的图片 }, error: (err) => { reject(err); // 压缩失败的错误信息 } }); }) } /** * 上传图片 */ export const uploadFile = async (imgObj, type, incidentId) => { console.log('44444', type) if(imgObj.extname=='mp4' || imgObj.extname=='avi' || imgObj.extname=='mpeg' || imgObj.extname=='wmv' || imgObj.extname=='mov' || imgObj.extname=='3gp' || imgObj.extname=='flv' || imgObj.extname=='mkv'){ return uni.uploadFile({ url: api_uploadAttachment(type, incidentId), filePath: imgObj.path, name: 'file', formData: { 'filename': imgObj.name } }) }else{ const res1 = await uni.getImageInfo({src: imgObj.url}); const res = res1[1]; 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 blob = await toBlob(canvas, imgObj) const fileSrc = await compressImage(blob) let tp = window.URL.createObjectURL(fileSrc) console.log('压缩后', tp); return uni.uploadFile({ timeout: 600000, url: api_uploadAttachment(type, incidentId), filePath: tp, name: 'file', formData: { 'filename': imgObj.name } }); } }