diff --git a/elastic/templates/elastic/upload.html b/elastic/templates/elastic/upload.html index 6cc1a75..e60eb28 100644 --- a/elastic/templates/elastic/upload.html +++ b/elastic/templates/elastic/upload.html @@ -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/', { @@ -381,4 +414,4 @@ document.getElementById('logoutBtn').addEventListener('click', async () => { }); - \ No newline at end of file +