packServer/backend/app/service/image_upload.js
liufumingren bde5dc7bad feat(backend): 图片上传接入腾讯云 COS,新增存储管理与未引用清理
- 头像 / 文档图片改由后端校验并转发到 COS,密钥只留在服务端
- 新增 file_records 登记表(迁移 20261123170000),记录对象键、大小、上传者等
- 引用关系实时计算(用户头像 / 文档正文),改删业务数据后状态自动同步
- 新增平台管理「存储管理」页:引用状态与明细、单删、两步清理未引用
- 新增接口 GET /api/web/admin/files、POST /api/web/admin/files/cleanup、
  DELETE /api/web/admin/files/:id(仍被引用默认 409,force 才删)
- COS 目录前缀(COS_DIR_AVATAR / COS_DIR_DOC)、大小上限、清理保护期改为可配置

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-23 16:39:47 +08:00

79 lines
2.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const { Service } = require('egg');
const crypto = require('crypto');
const path = require('path');
const IMAGE_TYPES = {
'.bmp': { mime: 'image/bmp', matches: buffer => buffer.toString('ascii', 0, 2) === 'BM' },
'.gif': {
mime: 'image/gif',
matches: buffer => [ 'GIF87a', 'GIF89a' ].includes(buffer.toString('ascii', 0, 6)),
},
'.jpeg': { mime: 'image/jpeg', matches: buffer => buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff },
'.jpg': { mime: 'image/jpeg', matches: buffer => buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff },
'.png': { mime: 'image/png', matches: buffer => buffer.toString('hex', 0, 8) === '89504e470d0a1a0a' },
'.webp': {
mime: 'image/webp',
matches: buffer => buffer.toString('ascii', 0, 4) === 'RIFF' && buffer.toString('ascii', 8, 12) === 'WEBP',
},
};
/**
* 图片上传:校验 → 生成对象键 → 交给 `service/fileStorage` 上传并登记
*
* 目录前缀来自 `config.cos.dirs`(env `COS_DIR_AVATAR` / `COS_DIR_DOC`),
* 需要按业务再分子目录时由调用方传 `dir`(例如头像按用户 ID 分目录)。
*/
class ImageUploadService extends Service {
/**
* @param {object} fileStream Egg multipart 文件流
* @param {object} [options] 选项
* @param {string} [options.category] avatar / doc(决定登记的业务分类)
* @param {string} [options.dir] 对象键前缀;不传用 `config.cos.dirs[category]`
* @return {Promise<object>} 登记后的文件信息
*/
async upload(fileStream, { category = 'doc', dir } = {}) {
const { ctx, config } = this;
const { maxFileSize, dirs } = config.cos;
const targetDir = String(dir || dirs[category] || 'images')
.replace(/\\/g, '/')
.replace(/^\/+|\/+$/g, '');
const filename = String(fileStream.filename || '').replace(/\\/g, '/').split('/').pop();
const extension = path.extname(filename).toLowerCase();
const imageType = IMAGE_TYPES[extension];
if (!imageType || fileStream.mime !== imageType.mime) {
ctx.throw(422, '仅支持 BMP、GIF、JPEG、PNG 或 WebP 图片');
}
const chunks = [];
let size = 0;
for await (const chunk of fileStream) {
size += chunk.length;
if (size > maxFileSize) {
fileStream.destroy();
ctx.throw(413, `图片不能超过 ${Math.ceil(maxFileSize / 1024 / 1024)} MB`);
}
chunks.push(chunk);
}
const buffer = Buffer.concat(chunks, size);
if (!imageType.matches(buffer)) {
ctx.throw(422, '图片内容与文件类型不匹配');
}
const key = `${targetDir}/${crypto.randomUUID()}${extension}`;
return ctx.service.fileStorage.uploadObject({
key,
body: buffer,
contentType: imageType.mime,
filename,
category,
uploader: ctx.state.user,
});
}
}
module.exports = ImageUploadService;