更新依赖项,使用 Busboy 替代 formidable 处理文件上传,优化上传逻辑,改进权限检查
This commit is contained in:
@@ -1,12 +1,15 @@
|
||||
import { useFileStore } from '@kevisual/use-config/file-store';
|
||||
import { checkAuth, error, router, writeEvents, getKey } from '../router.ts';
|
||||
import { IncomingForm } from 'formidable';
|
||||
import Busboy from 'busboy';
|
||||
import { app, minioClient } from '@/app.ts';
|
||||
|
||||
import { bucketName } from '@/modules/minio.ts';
|
||||
import { getContentType } from '@/utils/get-content-type.ts';
|
||||
import { User } from '@/models/user.ts';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { createWriteStream } from 'fs';
|
||||
import { pipeBusboy } from '@/modules/fm-manager/pipe-busboy.ts';
|
||||
import { ConfigModel } from '@/routes/config/models/model.ts';
|
||||
import { validateDirectory } from './util.ts';
|
||||
import { pick } from 'lodash-es';
|
||||
@@ -103,41 +106,79 @@ router.post('/api/s1/resources/upload', async (req, res) => {
|
||||
const share = !!url.searchParams.get('public');
|
||||
const meta = parseIfJson(url.searchParams.get('meta'));
|
||||
const noCheckAppFiles = !!url.searchParams.get('noCheckAppFiles');
|
||||
// 使用 formi dable 解析 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;
|
||||
const data = {
|
||||
progress: progress.toFixed(2),
|
||||
message: `Upload progress: ${progress.toFixed(2)}%`,
|
||||
};
|
||||
console.log('progress-upload', data);
|
||||
writeEvents(req, data);
|
||||
|
||||
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;
|
||||
const data = {
|
||||
progress: progress.toFixed(2),
|
||||
message: `Upload progress: ${progress.toFixed(2)}%`,
|
||||
};
|
||||
console.log('progress-upload', data);
|
||||
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);
|
||||
});
|
||||
// 解析上传的文件
|
||||
form.parse(req, async (err, fields, files) => {
|
||||
|
||||
busboy.on('finish', async () => {
|
||||
// 等待所有文件写入完成
|
||||
try {
|
||||
await Promise.all(filePromises);
|
||||
} catch (err) {
|
||||
logger.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) => {
|
||||
files.forEach((file) => {
|
||||
if (file?.filepath && fs.existsSync(file.filepath)) {
|
||||
fs.unlinkSync(file.filepath);
|
||||
}
|
||||
});
|
||||
};
|
||||
if (err) {
|
||||
logger.error(`Upload error: ${err.message}`);
|
||||
res.end(error(`Upload error: ${err.message}`));
|
||||
clearFiles();
|
||||
|
||||
// 检查是否有文件上传
|
||||
if (files.length === 0) {
|
||||
res.end(error('files is required'));
|
||||
return;
|
||||
}
|
||||
|
||||
let { appKey, version, username, directory, description } = getKey(fields, ['appKey', 'version', 'username', 'directory', 'description']);
|
||||
let uid = tokenUser.id;
|
||||
if (username) {
|
||||
@@ -170,7 +211,7 @@ router.post('/api/s1/resources/upload', async (req, res) => {
|
||||
return;
|
||||
}
|
||||
// 逐个处理每个上传的文件
|
||||
const uploadedFiles = Array.isArray(files.file) ? files.file : [files.file];
|
||||
const uploadedFiles = files;
|
||||
logger.info(
|
||||
'upload files',
|
||||
uploadedFiles.map((item) => {
|
||||
@@ -244,4 +285,6 @@ router.post('/api/s1/resources/upload', async (req, res) => {
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
pipeBusboy(req, res, busboy);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user