支持JPEG照片并保留原始尺寸

This commit is contained in:
2026-11-19 14:45:26 +08:00
parent 7520949b3b
commit 08f18b784f
5 changed files with 25 additions and 10 deletions
+1 -1
View File
@@ -4,7 +4,7 @@
## 活动记录
在一楼页面创建活动时默认选择“赋能中心一楼活动记录”,地点默认填“赋能中心一楼”。必须填写主题、时间,照片或 ZIP 至少提交一种。照片可直接从相册多选或拍照,支持 JPG、PNG、WebP,每次最多50张(含ZIP内照片),每张最大 8MB、2400 万像素。创建、编辑追加和成员补充材料均校验本次照片总数;历史照片保留,不占本次追加额度。逐张上传时显示“正在上传 3/7”及单张进度;失败重试会复用已成功上传的照片。直接上传接口每人24小时限额为1000张。
在一楼页面创建活动时默认选择“赋能中心一楼活动记录”,地点默认填“赋能中心一楼”。必须填写主题、时间,照片或 ZIP 至少提交一种。照片可直接从相册多选或拍照,支持 JPG、PNG、WebP 及常见 JPEG 变体;服务端统一转为 JPEG 存储,保留原始尺寸,不设像素上限。每次最多50张(含ZIP内照片),每张最大 8MB。创建、编辑追加和成员补充材料均校验本次照片总数;历史照片保留,不占本次追加额度。逐张上传时显示“正在上传 3/7”及单张进度;失败重试会复用已成功上传的照片。直接上传接口每人24小时限额为1000张。
ZIP 为可选附件,仅在附 PDF、Word、Excel、PowerPoint、TXT、CSV 或 Markdown 等文档时需要打包,不要求包内有照片。ZIP 最大100MB,包内单个文档最大50MB,照片每张最大8MB,展开后总大小不超过500MB;支持文件夹,不支持空ZIP、加密ZIP、链接、不安全路径及可执行文件。旧版含照片的ZIP继续支持,包内照片会自动提取展示。
+1 -1
View File
@@ -337,7 +337,7 @@
<div id="toast" class="toast hidden" role="status" aria-live="polite"></div>
<script src="/js/app.js?v=39"></script>
<script src="/js/app.js?v=40"></script>
</div>
</body>
</html>
+2 -2
View File
@@ -939,7 +939,7 @@
function centerUploadFields(prefix) {
return `<label>活动照片<input name="photos" type="file" accept="image/jpeg,image/png,image/webp" multiple /></label>
<p class="muted">可直接多选相册照片或拍照,每次最多${CENTER_PHOTO_BATCH_LIMIT}张(含ZIP内照片),每张不超过${CENTER_PHOTO_MAX_MB}MB。</p><div id="${prefix}-selected-photos" class="selected-photo-summary muted"></div>
<p class="muted">可直接多选相册照片或拍照,支持JPG、PNG、WebP并自动转为统一JPEG;每次最多${CENTER_PHOTO_BATCH_LIMIT}张(含ZIP内照片),每张不超过${CENTER_PHOTO_MAX_MB}MB。</p><div id="${prefix}-selected-photos" class="selected-photo-summary muted"></div>
<label>ZIP附件 <span class="hint-inline">(选填)</span><input name="materials" type="file" accept=".zip,application/zip" /></label>
<p class="muted">需要附PDF、Word、Excel等文档时再上传ZIP,最大${CENTER_ZIP_MAX_MB}MB,可不含照片。</p>`;
}
@@ -989,7 +989,7 @@
return async () => {
const files = [...form.photos.files], zip = form.materials.files[0];
if (files.length > CENTER_PHOTO_BATCH_LIMIT) throw new Error(`每次最多上传${CENTER_PHOTO_BATCH_LIMIT}张照片,请重新选择`);
if (files.some(file => file.size > CENTER_PHOTO_MAX_MB * MB || !(/\.(jpe?g|png|webp)$/i.test(file.name) || /^image\/(jpeg|png|webp)$/.test(file.type)))) throw new Error(`照片支持JPG、PNG、WebP,每张最大${CENTER_PHOTO_MAX_MB}MB`);
if (files.some(file => file.size > CENTER_PHOTO_MAX_MB * MB || !(/\.(jpe?g|jpg|jpeg|jpe|jfif|png|webp)$/i.test(file.name) || /^image\/(jpeg|jpg|jpe|jfif|pjpeg|png|webp)$/.test(file.type)))) throw new Error(`照片支持JPG、PNG、WebP,每张最大${CENTER_PHOTO_MAX_MB}MB`);
if (zip && (zip.size > CENTER_ZIP_MAX_MB * MB || !zip.name.toLowerCase().endsWith('.zip'))) throw new Error(`请提交${CENTER_ZIP_MAX_MB}MB以内的ZIP附件`);
if (files.length || zip) box.classList.remove('hidden');
for (let i = 0; i < files.length; i++) {
+7 -6
View File
@@ -14,6 +14,7 @@ from typing import Literal
from fastapi import Depends, HTTPException, Query, Request
from fastapi.responses import FileResponse
from PIL.Image import DecompressionBombError
from pydantic import BaseModel, Field, field_validator
from sqlalchemy import select, insert, update, delete, func, text, or_
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
@@ -224,13 +225,12 @@ async def material_photos(db, material_id, owner_id):
def convert_photo(raw):
from PIL import Image, ImageOps
with warnings.catch_warnings():
warnings.simplefilter('error', Image.DecompressionBombWarning)
warnings.simplefilter('error', Image.DecompressionBombError)
with Image.open(io.BytesIO(raw)) as image:
if image.format not in ('JPEG', 'PNG', 'WEBP') or image.width * image.height > 24000000:
raise ValueError('仅支持24百万像素以内的JPG、PNG、WebP照片')
if image.format not in ('JPEG', 'PNG', 'WEBP'):
raise ValueError('仅支持JPG、PNG、WebP照片')
image = ImageOps.exif_transpose(image).convert('RGB')
image.thumbnail((2400, 2400))
output = io.BytesIO(); image.save(output, 'JPEG', quality=85)
output = io.BytesIO(); image.save(output, 'JPEG', quality=90)
return output.getvalue()
@@ -303,7 +303,8 @@ def install(app, get_db, current_user, photo_root, visible_clause):
count = (await db.execute(select(func.count()).select_from(center_photos).where(center_photos.c.owner_id == viewer['id'], center_photos.c.created_at > now_ms() - 86400000))).scalar()
if count >= DAILY_PHOTO_LIMIT: raise HTTPException(429, f'今日照片上传已达{DAILY_PHOTO_LIMIT}张')
try: data = await asyncio.to_thread(convert_photo, bytes(raw))
except Exception as exc: raise HTTPException(422, '照片无效,仅支持JPG、PNG、WebP,最大24百万像素') from exc
except DecompressionBombError as exc: raise HTTPException(422, '图片数据过大,无法安全处理') from exc
except Exception as exc: raise HTTPException(422, '照片无效,仅支持JPG、PNG、WebP') from exc
key = uuid.uuid4().hex
folder = photo_root(); folder.mkdir(parents=True, exist_ok=True)
path = folder / (key + '.jpg')
+14
View File
@@ -1,6 +1,7 @@
import asyncio
import io
import tempfile
from PIL import Image
from pathlib import Path
from unittest.mock import patch
from sqlalchemy import insert, select
@@ -27,6 +28,19 @@ class DirectCenterPhotoTests(ApiTestCase):
self.assertEqual(result.status_code,200,result.text);ids.append(result.json()['id'])
return ids
async def test_jpeg_variants_convert_to_unified_original_size_jpeg(self):
owner=await register(self.client,'jpegvariants');headers=auth(owner['token'])
image=Image.new('RGB',(4021,237),'white')
raw=io.BytesIO();image.save(raw,'JPEG')
result=await self.client.post('/api/center/photos',headers=headers,content=raw.getvalue())
self.assertEqual(result.status_code,200,result.text)
photo=await self.client.get('/api/center/photos/'+result.json()['id'],headers=headers)
self.assertEqual(photo.status_code,200)
self.assertEqual(photo.headers['content-type'],'image/jpeg')
with Image.open(io.BytesIO(photo.content)) as stored:
self.assertEqual(stored.format,'JPEG')
self.assertEqual(stored.size,(4021,237))
async def test_photo_only_creation_supplement_and_edit_preserve_all_members_photos(self):
owner=await register(self.client,'directowner');member=await register(self.client,'directmember')
c=self.client;oh=auth(owner['token']);mh=auth(member['token'])