fea: 添加检测图片类型功能

This commit is contained in:
cancerai committed 2026-10-07 12:21:43 +08:00
1 parent 36058f2438
commit 53223ab812
3 files changed
+44 -1

No files matched your search

+22 -1
View File
@@ -1,3 +1,4 @@
import { fileTypeFromBuffer } from "file-type";
import { Hono } from "hono";
import { validator } from "hono/validator";
@@ -28,7 +29,7 @@ const app = appTmp.basePath("/watermark")
* param: outputType: 输出的文件类型,只允许 jpeg | png
*/
app.post("/encode",
validator("form", (val, c) => {
validator("form", async (val, c) => {
const image = val.image
const payload = val.payload
const strength = val.strength
@@ -62,6 +63,26 @@ app.post("/encode",
})
}
// 通过魔术数字判断文件真实类型
const imageBuffer = await (image as File).arrayBuffer()
const unit8Image = new Uint8Array(imageBuffer)
const imageType = await fileTypeFromBuffer(unit8Image)
if (!imageType) {
c.status(400)
return c.json({
code: 400,
msg: "Image type is invalid, must be jpeg or png"
})
}
if (!["image/png", "image/jpeg"].includes(imageType.mime)) {
c.status(400)
return c.json({
code: 400,
msg: "Image type is invalid, must be jpeg or png"
})
}
// DONE
const MAX_IMAGE_SIZE = 10 * 1024 * 1024
if ((image as File).size > MAX_IMAGE_SIZE) {
c.status(400)