feat(upload): compress images over 10MB before OSS upload (v3.4.13)

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-08-05 22:48:34 +08:00
parent bd1930f6b1
commit fa6fb80d19
15 changed files with 196 additions and 25 deletions
+34
View File
@@ -0,0 +1,34 @@
import Taro from '@tarojs/taro';
const MAX_BYTES = 10 * 1024 * 1024;
/** 小程序临时文件超过 10MB 时用 compressImage 压缩后再上传 */
export async function compressWeappImageIfNeeded(tempFilePath: string): Promise<string> {
if (process.env.TARO_ENV !== 'weapp') return tempFilePath;
let path = tempFilePath;
let size = await getFileSize(path);
if (size <= MAX_BYTES) return path;
const qualities = [80, 65, 50, 40];
for (const quality of qualities) {
const res = await Taro.compressImage({ src: path, quality });
path = res.tempFilePath;
size = await getFileSize(path);
if (size <= MAX_BYTES) return path;
}
if (size > MAX_BYTES) {
throw new Error('图片压缩后仍超过 10MB,请换一张较小的图片');
}
return path;
}
async function getFileSize(filePath: string): Promise<number> {
try {
const info = await Taro.getFileInfo({ filePath });
return typeof info.size === 'number' ? info.size : 0;
} catch {
return 0;
}
}