更新依赖项,使用 Busboy 替代 formidable 处理文件上传,优化上传逻辑,改进权限检查

This commit is contained in:
2025-12-21 06:41:27 +08:00
parent 15fcfdad18
commit 8a633feb4f
12 changed files with 344 additions and 155 deletions

View File

@@ -1,7 +1,7 @@
import { useFileStore } from '@kevisual/use-config/file-store';
import http from 'node:http';
import fs from 'fs';
import { IncomingForm } from 'formidable';
import Busboy from 'busboy';
import { app, minioClient } from '@/app.ts';
import { bucketName } from '@/modules/minio.ts';
@@ -11,6 +11,9 @@ import { getContainerById } from '@/routes/container/module/get-container-file.t
import { router, error, checkAuth, writeEvents } from './router.ts';
import './index.ts';
import { handleRequest as PageProxy } from './page-proxy.ts';
import path from 'path';
import { createWriteStream } from 'fs';
import { pipeBusboy } from '@/modules/fm-manager/pipe-busboy.ts';
const cacheFilePath = useFileStore('cache-file', { needExists: true });
router.get('/api/app/upload', async (req, res) => {
@@ -23,41 +26,80 @@ router.post('/api/app/upload', async (req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
const { tokenUser, token } = await checkAuth(req, res);
if (!tokenUser) return;
// 使用 formidable 解析 multipart/form-data
const form = new IncomingForm({
multiples: true, // 支持多文件上传
uploadDir: cacheFilePath, // 上传文件存储目录
allowEmptyFiles: true, // 允许空
minFileSize: 0, // 最小文件大小
createDirsFromUploads: false, // 根据上传的文件夹结构创建目录
keepExtensions: true, // 保留文件
hashAlgorithm: 'md5', // 文件哈希算法
// 使用 busboy 解析 multipart/form-data
const busboy = Busboy({ headers: req.headers });
const fields: any = {};
const files: any = [];
const filePromises: Promise<void>[] = [];
let bytesReceived = 0;
let bytesExpected = parseInt(req.headers['content-length'] || '0');
busboy.on('field', (fieldname, value) => {
fields[fieldname] = value;
});
form.on('progress', (bytesReceived, bytesExpected) => {
const progress = (bytesReceived / bytesExpected) * 100;
console.log(`Upload progress: ${progress.toFixed(2)}%`);
const data = {
progress: progress.toFixed(2),
message: `Upload progress: ${progress.toFixed(2)}%`,
};
writeEvents(req, data);
});
// 解析上传的文件
form.parse(req, async (err, fields, files) => {
if (err) {
res.end(error(`Upload error: ${err.message}`));
const uploadedFiles = Array.isArray(files.file) ? files.file : [files.file];
uploadedFiles.forEach((file) => {
fs.unlinkSync(file.filepath);
busboy.on('file', (fieldname, fileStream, info) => {
const { filename, encoding, mimeType } = info;
const tempPath = path.join(cacheFilePath, `${Date.now()}-${Math.random().toString(36).substring(7)}-${filename}`);
const writeStream = createWriteStream(tempPath);
const filePromise = new Promise<void>((resolve, reject) => {
fileStream.on('data', (chunk) => {
bytesReceived += chunk.length;
if (bytesExpected > 0) {
const progress = (bytesReceived / bytesExpected) * 100;
console.log(`Upload progress: ${progress.toFixed(2)}%`);
const data = {
progress: progress.toFixed(2),
message: `Upload progress: ${progress.toFixed(2)}%`,
};
writeEvents(req, data);
}
});
fileStream.pipe(writeStream);
writeStream.on('finish', () => {
files.push({
filepath: tempPath,
originalFilename: filename,
mimetype: mimeType,
});
resolve();
});
writeStream.on('error', (err) => {
reject(err);
});
});
filePromises.push(filePromise);
});
busboy.on('finish', async () => {
// 等待所有文件写入完成
try {
await Promise.all(filePromises);
} catch (err) {
console.error(`File write error: ${err.message}`);
res.end(error(`File write error: ${err.message}`));
return;
}
const clearFiles = () => {
const uploadedFiles = Array.isArray(files.file) ? files.file : [files.file];
uploadedFiles.forEach((file) => {
fs.unlinkSync(file.filepath);
files.forEach((file: any) => {
if (file?.filepath && fs.existsSync(file.filepath)) {
fs.unlinkSync(file.filepath);
}
});
};
// 检查是否有文件上传
if (files.length === 0) {
res.end(error('files is required'));
return;
}
let appKey,
version,
username = '';
@@ -99,11 +141,9 @@ router.post('/api/app/upload', async (req, res) => {
console.log('Appkey', appKey, version);
// 逐个处理每个上传的文件
const uploadedFiles = Array.isArray(files.file) ? files.file : [files.file];
const uploadResults = [];
for (let i = 0; i < uploadedFiles.length; i++) {
const file = uploadedFiles[i];
// @ts-ignore
for (let i = 0; i < files.length; i++) {
const file = files[i];
const tempPath = file.filepath; // 文件上传时的临时路径
const relativePath = file.originalFilename; // 保留表单中上传的文件名 (包含文件夹结构)
// 比如 child2/b.txt
@@ -144,6 +184,8 @@ router.post('/api/app/upload', async (req, res) => {
}
res.end(JSON.stringify(data));
});
pipeBusboy(req, res, busboy);
});
router.get('/api/container/file/:id', async (req, res) => {