'use strict'; const { Controller } = require('egg'); const crypto = require('crypto'); const fs = require('fs'); const fsp = require('fs/promises'); const path = require('path'); const { parsePagination, buildPageResult } = require('../lib/pagination'); /** 允许上传的图片扩展名(与 config.multipart.whitelist 保持一致) */ const ALLOWED_EXT = [ '.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg' ]; /** 扩展名 -> Content-Type,供 raw 接口回写响应头 */ const MIME = { '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.gif': 'image/gif', '.bmp': 'image/bmp', '.webp': 'image/webp', '.svg': 'image/svg+xml', }; /** raw 访问路径必须形如「主体ID/年/月/日/hash.ext」,非法路径(含 .. 穿越)一律拒绝 */ const RAW_PATH_RE = /^\d+\/\d{4}\/\d{2}\/\d{2}\/[a-f0-9]{64}\.[a-z0-9]+$/; const pad2 = num => String(num).padStart(2, '0'); /** 流式计算文件 SHA256,避免大图整块读入内存 */ function sha256File(filepath) { return new Promise((resolve, reject) => { const hash = crypto.createHash('sha256'); fs.createReadStream(filepath) .on('data', chunk => hash.update(chunk)) .on('end', () => resolve(hash.digest('hex'))) .on('error', reject); }); } /** 临时目录与上传目录可能不在同一磁盘(EXDEV),先尝试 rename,失败再复制 */ async function moveFile(from, to) { try { await fsp.rename(from, to); } catch (err) { if (err.code !== 'EXDEV') throw err; await fsp.copyFile(from, to); await fsp.unlink(from); } } /** * @controller FileController 文件资源管理 */ class FileController extends Controller { /** * @summary 文件列表 * @description 分页查询当前主体已上传的文件资源 * @router get /api/files * @apikey * @request query integer page 页码,默认 1 * @request query integer pageSize 每页条数,默认 20 * @request query integer principal_id 所属主体ID(必填,需当前账号已绑定该主体) * @request query string keyword 关键词,模糊匹配原始文件名 * @response 200 fileListResponse success */ async index() { const { ctx, app } = this; const Op = app.Sequelize.Op; const { page, pageSize, offset, limit } = parsePagination(ctx.query); const keyword = (ctx.query.keyword || '').trim(); const where = { principal_id: ctx.state.principalId }; if (keyword) where.name = { [Op.like]: `%${keyword}%` }; const { count, rows } = await ctx.model.File.findAndCountAll({ where, offset, limit, order: [[ 'id', 'DESC' ]], }); ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) }; } /** * @summary 文件去重预检 * @description 上传前按内容 SHA256 批量查验,命中的文件直接复用已有 URL,无需重复上传 * @router post /api/files/check * @apikey * @request body checkFilesRequest *body * @response 200 fileCheckResponse success */ async check() { const { ctx } = this; const hashes = ctx.request.body.hashes; if (!Array.isArray(hashes) || !hashes.length) { ctx.body = { code: 0, message: 'success', data: [] }; return; } const rows = await ctx.model.File.findAll({ where: { principal_id: ctx.state.principalId, hash: hashes.slice(0, 100).map(String), }, }); ctx.body = { code: 0, message: 'success', data: rows }; } /** * @summary 上传文件 * @description 单文件上传(表单字段 file,仅图片)。按内容 SHA256 在当前主体内去重: * 命中已有记录直接返回其 URL,不重复落盘;未命中则按「主体ID/年/月/日」分目录存储,文件名为内容 hash * @router post /api/files/upload * @apikey * @request formData file *file 图片文件 * @request formData integer principal_id 所属主体ID(必填,需当前账号已绑定该主体) * @response 200 fileUploadResponse success */ async upload() { const { ctx, app } = this; const principalId = ctx.state.principalId; const files = ctx.request.files || []; if (!files.length) { ctx.status = 400; ctx.body = { code: 400, message: '未接收到上传文件(表单字段名 file)' }; return; } const file = files.find(item => item.field === 'file') || files[0]; const originalName = file.filename || path.basename(file.filepath); const ext = path.extname(originalName).toLowerCase(); if (!ALLOWED_EXT.includes(ext)) { await ctx.cleanupRequestFiles(); ctx.status = 400; ctx.body = { code: 400, message: `仅支持上传图片:${ALLOWED_EXT.join('、')}` }; return; } // 1) 内容 hash:既是去重依据,也是落盘文件名 const hash = await sha256File(file.filepath); const stat = await fsp.stat(file.filepath); // 2) 主体内已存在同一份文件:直接复用,丢弃临时文件 const exist = await ctx.model.File.findOne({ where: { principal_id: principalId, hash }, }); if (exist) { await ctx.cleanupRequestFiles(); ctx.body = { code: 0, message: 'success', data: { ...exist.toJSON(), deduped: true } }; return; } // 3) 未命中:按上传时间(年/月/日)分目录,并挂在主体目录下实现资源隔离 const now = new Date(); const relDir = path.posix.join( String(principalId), String(now.getFullYear()), pad2(now.getMonth() + 1), pad2(now.getDate()) ); const relPath = path.posix.join(relDir, `${hash}${ext}`); await fsp.mkdir(path.join(app.config.upload.dir, relDir), { recursive: true }); await moveFile(file.filepath, path.join(app.config.upload.dir, relPath)); await ctx.cleanupRequestFiles(); const payload = { principal_id: principalId, hash, name: originalName, ext, mime: file.mime || file.mimeType || '', size: stat.size, path: relPath, url: `${app.config.upload.urlPrefix}/${relPath}`, }; try { const saved = await ctx.model.File.create(payload); ctx.body = { code: 0, message: 'success', data: { ...saved.toJSON(), deduped: false } }; } catch (err) { // 并发上传同一文件时唯一索引冲突,回读已有记录返回 if (err.name === 'SequelizeUniqueConstraintError') { const record = await ctx.model.File.findOne({ where: { principal_id: principalId, hash }, }); ctx.body = { code: 0, message: 'success', data: { ...record.toJSON(), deduped: true } }; return; } throw err; } } /** * @summary 读取文件 * @description 按存储相对路径读取文件内容。路径形如「主体ID/年/月/日/hash.ext」, * 由上传接口返回,URL 不可枚举;公开读取便于 img 标签直接引用 * @router get /api/files/raw/{path} * @request path string *path 存储相对路径,形如 1/2026/09/11/{hash}.png * @response 200 baseResponse 文件二进制流,Content-Type 由扩展名决定 */ async raw() { const { ctx, app } = this; const relPath = String(ctx.params[0] || ''); if (!RAW_PATH_RE.test(relPath)) { ctx.status = 400; ctx.body = { code: 400, message: '文件路径不合法' }; return; } const rootDir = path.resolve(app.config.upload.dir); const absFile = path.resolve(rootDir, relPath); if (!absFile.startsWith(rootDir + path.sep) || !fs.existsSync(absFile)) { ctx.status = 404; ctx.body = { code: 404, message: '文件不存在' }; return; } ctx.type = MIME[path.extname(absFile).toLowerCase()] || 'application/octet-stream'; // 文件名即内容 hash,内容永不变化,可长期强缓存 ctx.set('Cache-Control', 'public, max-age=31536000, immutable'); ctx.body = fs.createReadStream(absFile); } } module.exports = FileController;