修复了不支持webp格式的图片上传的问题
All checks were successful
CI / docker-ci (push) Has been skipped

This commit is contained in:
2025-11-27 12:11:58 +08:00
parent d001fec21e
commit 835426b133

View File

@@ -139,6 +139,32 @@ const dropArea = document.getElementById('dropArea');
let currentImageRel = '';
async function convertToJpeg(file){
const url = URL.createObjectURL(file);
let img;
try{
const blob = await fetch(url).then(r=>r.blob());
img = await createImageBitmap(blob);
}catch(e){
img = await new Promise((resolve,reject)=>{const i=new Image();i.onload=()=>resolve(i);i.onerror=reject;i.src=url;});
}
URL.revokeObjectURL(url);
const maxDim = 2000;
const w = img.width;
const h = img.height;
const scale = Math.min(1, maxDim/Math.max(w,h));
const nw = Math.round(w*scale);
const nh = Math.round(h*scale);
const canvas = document.createElement('canvas');
canvas.width = nw;
canvas.height = nh;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, nw, nh);
const blob = await new Promise(resolve=>canvas.toBlob(resolve,'image/jpeg',0.82));
const name = (file.name||'image').replace(/\.[^/.]+$/, '') + '.jpg';
return new File([blob], name, {type:'image/jpeg'});
}
// 拖拽上传功能
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
dropArea.addEventListener(eventName, preventDefaults, false);
@@ -289,8 +315,15 @@ uploadForm.addEventListener('submit', async (e) => {
return;
}
let jpegFile = file;
try {
jpegFile = await convertToJpeg(file);
preview.src = URL.createObjectURL(jpegFile);
} catch (_) {
jpegFile = file;
}
const formData = new FormData();
formData.append('file', file);
formData.append('file', jpegFile);
try {
const resp = await fetch('/elastic/upload/', {