提交 3348f60a authored 作者: 国王's avatar 国王

Revert "feat(upload): 上传前压缩图片,单文件上限按 10MB 处理"

This reverts commit acae53e6.
上级 acae53e6
import request from '@/H5Public/utils/request';
import config from '@/config';
import config from '@/config/config';
import { getToken } from '@/H5Public/utils/authority';
// onestop 服务根地址:优先取平台配置,缺省回退到当前站点
const ONESTOP_BASE =
config.sqlFormsServer || `${window.location.origin}/produce/v1/api/onestop`;
// 服务端单文件上限(onestop /upload 的 spring.servlet.multipart.max-file-size)
// 后端已按 10MB 规划;未调整前接口仍是 Spring 默认 1MB,见下面的自动降级逻辑
export const MAX_UPLOAD_BYTES = 10 * 1024 * 1024;
// 后端仍是 1MB 上限时的压缩目标
const SMALL_UPLOAD_BYTES = 900 * 1024;
// 压缩目标:留一点余量给 multipart 包头,只有超过这个体积的图片才压缩
const COMPRESS_TARGET_BYTES = MAX_UPLOAD_BYTES - 512 * 1024;
// 压缩后长边上限,兼顾清晰度和体积
const MAX_IMAGE_SIDE = 1600;
// 兼容不支持 canvas 解码的格式(heic/heif 等)
const IMAGE_RE = /\.(png|jpe?g|gif|bmp|webp)$/i;
// 记录本次会话是否已发现后端只接受约 1MB 的文件
const SIZE_LIMITED_KEY = 'onestop-upload-size-limited';
const isImageFile = file =>
(file.type || '').indexOf('image/') === 0 || IMAGE_RE.test(file.name || '');
const isSizeLimited = () => {
try {
return window.sessionStorage.getItem(SIZE_LIMITED_KEY) === '1';
} catch (e) {
return false;
}
};
const markSizeLimited = () => {
try {
window.sessionStorage.setItem(SIZE_LIMITED_KEY, '1');
} catch (e) {
// 隐私模式下 sessionStorage 不可用,忽略即可
}
};
const formatLimit = bytes => `${Math.round(bytes / 1024 / 1024)}MB`;
function getFileUrl(params = {}, url) {
return request(config.folderServer + url, {
......@@ -48,179 +10,23 @@ function getFileUrl(params = {}, url) {
});
}
export const uploadFile = (params = {}) => {
export const uploadFile = (params ={}) => {
return getFileUrl(params, '/uploadFileApi/upload');
};
function loadImage(file) {
return new Promise((resolve, reject) => {
const objectUrl = URL.createObjectURL(file);
const image = new Image();
image.onload = () => {
URL.revokeObjectURL(objectUrl);
resolve(image);
};
image.onerror = () => {
URL.revokeObjectURL(objectUrl);
reject(new Error('图片解析失败,请重新拍照或选择图片'));
};
image.src = objectUrl;
});
}
// 兼容不支持 canvas.toBlob 的旧内核(部分安卓微信)
function canvasToBlob(canvas, type, quality) {
return new Promise(resolve => {
if (canvas.toBlob) {
canvas.toBlob(blob => resolve(blob), type, quality);
return;
}
try {
const dataUrl = canvas.toDataURL(type, quality);
const binary = window.atob(dataUrl.split(',')[1] || '');
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
resolve(new Blob([bytes], { type }));
} catch (e) {
resolve(null);
}
});
}
/**
* 压缩图片到 targetBytes 以内:先按长边缩放,再逐级降低 jpeg 质量,仍超出时继续缩小尺寸。
*/
export function compressImage(file, targetBytes, maxSide = MAX_IMAGE_SIDE) {
return loadImage(file).then(image => {
const longest = Math.max(image.width, image.height) || 1;
let scale = longest > maxSide ? maxSide / longest : 1;
let quality = 0.82;
let result = null;
const step = () => {
const canvas = document.createElement('canvas');
canvas.width = Math.max(1, Math.round(image.width * scale));
canvas.height = Math.max(1, Math.round(image.height * scale));
const ctx = canvas.getContext('2d');
// 透明图片转 jpeg 需要白底,否则会变黑
ctx.fillStyle = '#fff';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
return canvasToBlob(canvas, 'image/jpeg', quality).then(blob => {
if (!blob) return null;
result = blob;
if (blob.size <= targetBytes) return blob;
if (quality > 0.55) {
quality = Math.max(0.55, quality - 0.12);
} else {
scale *= 0.75;
}
return step();
});
};
return step().then(() => {
if (!result || result.size > targetBytes) return null;
const name = String(file.name || 'image').replace(/\.[^.]+$/, '') || 'image';
return new File([result], `${name}.jpg`, { type: 'image/jpeg' });
});
});
}
/**
* 上传前的预处理:超过目标体积的图片自动压缩;文档等无法压缩的直接给出明确提示。
*/
export function prepareUploadFile(file, targetBytes = COMPRESS_TARGET_BYTES) {
if (!file) return Promise.reject(new Error('没有选择文件'));
if (file.size <= targetBytes) return Promise.resolve(file);
if (!isImageFile(file)) {
return Promise.reject(new Error(`「${file.name}」超过 ${formatLimit(targetBytes)},请压缩后再上传`));
}
return compressImage(file, targetBytes).then(compressed => {
if (!compressed) {
throw new Error(`「${file.name}」压缩后仍超过 ${formatLimit(targetBytes)},请重新拍照或选择`);
}
return compressed;
});
}
function postFile(file) {
const token = getToken() || '';
export function uploadOnestopFile(file) {
let url = config.sqlFormsServer + '/upload';
const formData = new FormData();
formData.append('file', file);
formData.append('token', token);
const headers = {
Authorization: `bearer ${token}`,
Accept: '*/*',
};
// 只在开发环境带 env 头;生产环境不要出现值为 undefined 的 header
if (process.env.NODE_ENV === 'development') headers.env = 'test';
return fetch(`${ONESTOP_BASE}/upload`, {
formData.append('token', getToken());
return fetch(url, {
method: 'POST',
credentials: 'include',
headers,
headers: {
Authorization: `bearer ${getToken()}`,
Accept: '*/*',
env: process.env.NODE_ENV === 'development' ? 'test' : undefined,
},
body: formData,
}).then(response => {
if (!response.ok) {
const error = new Error(`上传失败(${response.status}),请稍后重试`);
error.status = response.status;
throw error;
}
return response.text();
});
}).then(response => response.text());
}
function parsePath(text) {
const result = (text || '').trim();
if (!result) throw new Error('上传失败:服务端未返回文件地址');
let path = result;
if (result[0] === '"') {
try {
path = JSON.parse(result);
} catch (e) {
path = result;
}
}
path = typeof path === 'string' ? path.trim() : '';
const isUrl = /^https?:\/\//i.test(path);
if (!isUrl && path.charAt(0) !== '/') {
throw new Error('上传失败:服务端返回异常,请稍后重试');
}
return path;
}
function uploadWithLimit(file, targetBytes) {
return prepareUploadFile(file, targetBytes)
.then(postFile)
.then(parsePath);
}
/**
* 上传文件到 onestop(手写签名、证明资料、销假附件共用)。
* 接口返回纯文本相对路径(如 /u/202611/xxx.png),也兼容被 JSON 序列化的情况。
* - 默认按 10MB 上限:只有超过 9MB 的图片才压缩,原图可直接上传
* - 若后端仍是 Spring 默认的 1MB 上限(上传返回 500),自动压缩到 900KB 重试一次,
* 并在本次会话内记住该限制,后续大图直接压缩上传
* - 非 2xx、空响应、非相对路径/URL(如登录页 HTML)都会抛错
*/
export function uploadOnestopFile(file) {
if (!file) return Promise.reject(new Error('没有选择文件'));
const limited = isSizeLimited();
const target = limited ? SMALL_UPLOAD_BYTES : COMPRESS_TARGET_BYTES;
return uploadWithLimit(file, target).catch(error => {
const canRetry =
!limited &&
error &&
error.status === 500 &&
isImageFile(file) &&
file.size > SMALL_UPLOAD_BYTES;
if (!canRetry) throw error;
markSizeLimited();
return uploadWithLimit(file, SMALL_UPLOAD_BYTES);
});
}
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论