From 3f2b6f6d5f4a258937a5087a6d3da70f86899a50 Mon Sep 17 00:00:00 2001 From: Cxx0822 <1556464090@qq.com> Date: Tue, 7 Apr 2026 23:25:16 +0800 Subject: [PATCH] =?UTF-8?q?feat:=E5=A2=9E=E5=8A=A0=E9=9D=9E=E5=9B=BE?= =?UTF-8?q?=E7=89=87=E6=A0=BC=E5=BC=8F=E7=9A=84=E6=96=87=E4=BB=B6=E5=A4=84?= =?UTF-8?q?=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app.js | 49 +++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 43 insertions(+), 6 deletions(-) diff --git a/app.js b/app.js index 200fe54..38edd5b 100644 --- a/app.js +++ b/app.js @@ -9,6 +9,35 @@ const {sendResponse, isSafePath, processImage} = require("./utils"); const PORT = process.env.PORT || 3000; const IMAGE_BASE_DIR = process.env.IMAGE_BASE_DIR || '/app/images'; +// 定义支持的图片扩展名 +const IMAGE_EXTENSIONS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg', 'tiff', 'tif']); + +// MIME 类型映射 +const MIME_TYPES = { + 'jpg': 'image/jpeg', + 'jpeg': 'image/jpeg', + 'png': 'image/png', + 'gif': 'image/gif', + 'webp': 'image/webp', + 'bmp': 'image/bmp', + 'svg': 'image/svg+xml', + 'tiff': 'image/tiff', + 'tif': 'image/tiff', + 'mp4': 'video/mp4', + 'webm': 'video/webm', + 'ogg': 'video/ogg', + 'avi': 'video/x-msvideo', + 'mov': 'video/quicktime', + 'mp3': 'audio/mpeg', + 'wav': 'audio/wav', + 'pdf': 'application/pdf', + 'txt': 'text/plain', + 'html': 'text/html', + 'css': 'text/css', + 'js': 'application/javascript', + 'json': 'application/json' +}; + const server = http.createServer(async (req, res) => { if (req.method !== 'GET') { return sendResponse(res, 405, '仅支持GET请求'); @@ -33,15 +62,23 @@ const server = http.createServer(async (req, res) => { } if (!fs.existsSync(fullImagePath)) { - return sendResponse(res, 404, `图片不存在:${requestedFilePath}`); + return sendResponse(res, 404, `文件不存在:${requestedFilePath}`); } - // 如果没有压缩参数,直接返回原图 - if (!query.q && !query.w && !query.width && !query.h && !query.height) { + // 获取文件扩展名 + const ext = path.extname(fullImagePath).toLowerCase().slice(1); + const isImage = IMAGE_EXTENSIONS.has(ext); + const hasImageParams = query.q || query.w || query.width || query.h || query.height; + + // 如果不是图片文件,或者图片文件但没有处理参数,直接返回原文件 + if (!isImage || !hasImageParams) { const fileStream = fs.createReadStream(fullImagePath); - const ext = path.extname(fullImagePath).slice(1); - res.writeHead(200, {'Content-Type': `image/${ext}`}); - // 流式传输文件(适合大文件) + + // 设置正确的 Content-Type + const contentType = MIME_TYPES[ext] || 'application/octet-stream'; + res.writeHead(200, {'Content-Type': contentType}); + + // 流式传输文件 fileStream.pipe(res); fileStream.on('error', (err) => { sendResponse(res, 500, `读取文件失败:${err.message}`);