?首先是npm install?compressorjs
然后新建一個compressorjs.js的文件
import Compressor from "compressorjs";// 默認壓縮配置 const DEFAULT_COMPRESS_OPTIONS = {quality: 0.6, // 默認壓縮質量 (0-1)maxWidth: 1920, // 最大寬度maxHeight: 1080, // 最大高度convertSize: 5 * 1024 * 1024, // 超過5MB的圖片轉為WebP };/*** 壓縮圖片文件* @param {File} file - 待壓縮的圖片文件* @param {Object} options - 壓縮配置項* @returns {Promise<File>} 壓縮后的文件*/ export function compressImage(file, options = {}) {return new Promise((resolve, reject) => {// 合并配置并限制最小壓縮質量const mergedOptions = {...DEFAULT_COMPRESS_OPTIONS,...options,quality: Math.max(0.1,options.quality ?? DEFAULT_COMPRESS_OPTIONS.quality),maxWidth: Math.min(options.maxWidth ?? DEFAULT_COMPRESS_OPTIONS.maxWidth,8192),maxHeight: Math.min(options.maxHeight ?? DEFAULT_COMPRESS_OPTIONS.maxHeight,8192),};// 執行壓縮new Compressor(file, {...mergedOptions,success(result) {if (!result) {return reject(new Error("Compression result is empty"));}resolve(new File([result], file.name, { type: result.type }));},error(err) {reject(err);},});}); }
?
具體的使用頁面。只用在上傳之前before-upload的函數中壓縮就可以啦
<el-upload:before-upload="beforeUploadImg"
>
</el-upload>
?
import { compressImage } from "@/utils/imageCompress";async beforeUploadImg(file) {const fileSize = file.size / 1024 / 1024;let types = ["image/jpeg", "image/jpg", "image/png", "application/pdf"];const isImageOrPDF = types.includes(file.type);if (!isImageOrPDF) {this.$message.error("上傳圖片只能是 JPG/JPEG/PNG/PDF 格式!");return false;}try {// 壓縮圖片(僅處理大于5MB的圖片)。當前你也可以不加這個限制就是壓縮所有上傳的圖片if (fileSize > 5) {const compressedFile = await compressImage(file, {quality: fileSize > 10 ? 0.7 : 1,axWidth: Infinity, // 不限制寬度maxHeight: Infinity, // 不限制高度});return compressedFile; // 返回壓縮后的文件}return file;} catch (err) {if (fileSize > 5) {this.$message({message: "上傳圖片大小超過限制",type: "warning",});return false;}console.error("壓縮失敗:", err);return file; // 降級處理:上傳原文件}
}
?