Files
SupplierSystem/src/utils/imageFileLimits.ts
T
雨天 19a964ccde
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
Web验收拍照识别 + 修上传失败
① Web 验收拍照/拖入后自动 AI 识别(复用库存入库识别,预填
规格/生产日期/保质期/产地,只补空、切单丢弃过期响应,零新增文案)。
② 修「拍照后上传失败」:根因是照片 dataURL 内联在提交体,而全局
express.json 仅 2mb 且照片不降尺寸/质量 0.92 ⇒ 大图必 413。
甲:照片先降尺寸再画水印(≤1600px / q0.8,对齐小程序);
丙:仅把 /api/workflow/inspection/submit 体上限放宽到 20mb。
③ 小程序逐张上传单张失败不中断整批 + 汇总提示。
新增契约测试;门禁与全量回归对基线。
2026-10-16 18:15:08 +08:00

184 lines
6.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
export const GENERAL_IMAGE_LIMITS = {
maxFileSizeBytes: 5 * 1024 * 1024,
acceptedTypes: ['image/jpeg', 'image/png', 'image/webp'],
acceptedExtensions: ['jpg', 'jpeg', 'png', 'webp'],
};
export function isGeneralImageFile(file: File): boolean {
if (file.type && GENERAL_IMAGE_LIMITS.acceptedTypes.includes(file.type)) return true;
const ext = file.name.split('.').pop()?.toLowerCase();
return Boolean(ext && GENERAL_IMAGE_LIMITS.acceptedExtensions.includes(ext));
}
import { pickFileFromDataTransfer } from './fileDrop';
export function getImageFileFromDataTransfer(dataTransfer: DataTransfer | null): File | null {
return pickFileFromDataTransfer(dataTransfer, isGeneralImageFile);
}
export function dataTransferHasImageFiles(dataTransfer: DataTransfer | null): boolean {
if (!dataTransfer) return false;
return Array.from(dataTransfer.types || []).some(
(type) =>
type === 'Files' ||
type === 'application/x-moz-file' ||
type === 'public.file-url' ||
type.startsWith('image/')
);
}
export const ORDER_RECOGNITION_IMAGE_LIMITS = {
maxFileSizeBytes: 2 * 1024 * 1024,
maxDimension: 1600,
quality: 0.82,
acceptedTypes: ['image/jpeg', 'image/png', 'image/webp'],
};
export function validateGeneralImageFile(file: File): string | null {
if (!isGeneralImageFile(file)) {
return '仅支持 JPG、PNG、WEBP 图片';
}
if (file.size > GENERAL_IMAGE_LIMITS.maxFileSizeBytes) {
return '图片不能超过 5MB';
}
return null;
}
function loadImageFromDataUrl(dataUrl: string): Promise<HTMLImageElement> {
return new Promise((resolve, reject) => {
const image = new Image();
image.onload = () => resolve(image);
image.onerror = () => reject(new Error('图片读取失败,请重试'));
image.src = dataUrl;
});
}
function readFileAsDataUrl(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => resolve(String(reader.result || ''));
reader.onerror = () => reject(new Error('图片读取失败,请重试'));
reader.readAsDataURL(file);
});
}
/**
* 验收存档照片上限:最长边 ≤1600px、JPEG 质量 0.8 —— 与小程序 `utils/orderImage.js`
* (`MAX_DIMENSION = 1600` / `COMPRESS_QUALITY = 80`)**同口径**。
*
* 为什么必须降尺寸:Web 验收把照片作为 **dataURL 内联**在提交体里(`POST /inspection/submit`),
* 而全局 `express.json({ limit: '2mb' })` ⇒ 原图不缩 + 质量 0.92 时,一张 5MB 原图可达 4~6MB,
* 直接 413「上传失败」(同族先例见 docs/design/20260921-quality-report-upload-multer-channel.md)。
*/
export const INSPECTION_PHOTO_MAX_DIMENSION = 1600;
const INSPECTION_PHOTO_JPEG_QUALITY = 0.8;
export async function loadOrientedCanvasFromFile(file: File): Promise<HTMLCanvasElement> {
if (typeof createImageBitmap === 'function') {
try {
const bitmap = await createImageBitmap(file, { imageOrientation: 'from-image' });
try {
const canvas = document.createElement('canvas');
canvas.width = bitmap.width;
canvas.height = bitmap.height;
const context = canvas.getContext('2d');
if (!context) throw new Error('浏览器不支持图片处理');
context.drawImage(bitmap, 0, 0);
return canvas;
} finally {
bitmap.close();
}
} catch {
// fall back to Image() below
}
}
const originalDataUrl = await readFileAsDataUrl(file);
const image = await loadImageFromDataUrl(originalDataUrl);
const canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
const context = canvas.getContext('2d');
if (!context) {
throw new Error('浏览器不支持图片处理');
}
context.drawImage(image, 0, 0);
return canvas;
}
export async function renderInspectionPhotoWithWatermark(
file: File,
meta: { orderCode?: string; branchName?: string }
): Promise<string> {
const source = await loadOrientedCanvasFromFile(file);
/**
* ⚠️ 顺序:**先降尺寸、再画水印**。
* 若先画水印再缩,水印字会被一起缩小到不可读;降尺寸后画,水印相对更清晰。
*/
const maxSide = Math.max(source.width, source.height);
const scale =
maxSide > INSPECTION_PHOTO_MAX_DIMENSION ? INSPECTION_PHOTO_MAX_DIMENSION / maxSide : 1;
let canvas = source;
if (scale < 1) {
const resized = document.createElement('canvas');
resized.width = Math.max(1, Math.round(source.width * scale));
resized.height = Math.max(1, Math.round(source.height * scale));
const resizedContext = resized.getContext('2d');
if (!resizedContext) {
throw new Error('浏览器不支持图片处理');
}
resizedContext.drawImage(source, 0, 0, resized.width, resized.height);
canvas = resized;
}
const context = canvas.getContext('2d');
if (!context) {
throw new Error('浏览器不支持图片处理');
}
const timestamp = new Date().toLocaleString();
const orderCode = String(meta.orderCode || '').trim();
const branchName = String(meta.branchName || '分公司').trim() || '分公司';
context.font = 'bold 24px Arial';
context.fillStyle = 'rgba(255, 255, 255, 0.85)';
context.fillText(`验收拍照 ${timestamp}`, 20, canvas.height - 40);
if (orderCode) {
context.fillText(`订单: ${orderCode}`, 20, canvas.height - 15);
}
context.fillText(branchName, 20, canvas.height - 65);
return canvas.toDataURL('image/jpeg', INSPECTION_PHOTO_JPEG_QUALITY);
}
export async function compressOrderRecognitionImage(file: File): Promise<string> {
if (!isGeneralImageFile(file)) {
throw new Error('仅支持 JPG、PNG、WEBP 图片');
}
const originalDataUrl = await readFileAsDataUrl(file);
const image = await loadImageFromDataUrl(originalDataUrl);
const scale = Math.min(
1,
ORDER_RECOGNITION_IMAGE_LIMITS.maxDimension / Math.max(image.width, image.height)
);
const width = Math.max(1, Math.round(image.width * scale));
const height = Math.max(1, Math.round(image.height * scale));
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const context = canvas.getContext('2d');
if (!context) {
throw new Error('浏览器不支持图片压缩,请更换浏览器或上传更小图片');
}
context.drawImage(image, 0, 0, width, height);
const compressed = canvas.toDataURL('image/jpeg', ORDER_RECOGNITION_IMAGE_LIMITS.quality);
const estimatedBytes = Math.ceil((compressed.split(',')[1]?.length || 0) * 0.75);
if (estimatedBytes > ORDER_RECOGNITION_IMAGE_LIMITS.maxFileSizeBytes) {
throw new Error('图片压缩后仍超过2MB,请重新拍照或裁剪后上传');
}
return compressed;
}