引言
文件上传看似简单,直到遇到大文件、慢网络、恶意内容和并发重试。设计目标是流式处理、可恢复、可验证,并且不把不可信文件直接暴露给用户。
不要整体缓冲
把整个文件读进内存会在并发上传时耗尽进程。使用流式解析和写入,或让客户端直接上传到对象存储,服务端只签发受限的预签名 URL。限制请求体大小和超时。
先验证再存储
在上传前校验声明的大小和类型只是 UX;服务端必须重新检查实际字节、文件签名和内容。生成自己的存储文件名,绝不使用客户端文件名作为路径。上传目录放在 Web 根目录之外。
分块与可恢复
大文件分块上传,记录 upload id 和已完成分块。客户端断线后从断点继续,服务端校验分块哈希并在完成后合并。分块接口要幂等,重复上传同一块不应产生重复数据。
扫描与隔离
文件先进入隔离区,异步进行病毒扫描和内容检查,通过后才移动到可下载位置。扫描失败要阻断下载并告警。记录上传者、哈希和扫描结果,便于追溯和去重。
结论
上传系统的核心是不可信输入和资源边界。流式处理、服务端校验、隔离扫描和可恢复传输共同构成可靠的上传路径。
代码示例
import { createWriteStream } from "node:fs";
import { pipeline } from "node:stream/promises";
import { randomUUID } from "node:crypto";
async function streamUpload(req: Request, destDir: string): Promise<{ path: string; size: number }> {
const id = randomUUID();
const dest = `${destDir}/${id}.tmp`;
let size = 0;
// Track bytes as they flow, enforcing the size limit mid-stream.
const counter = new Transform({
transform(chunk, _enc, cb) {
size += chunk.length;
if (size > MAX_BYTES) cb(new Error("file too large"));
else cb(null, chunk);
},
});
await pipeline(req.body, counter, createWriteStream(dest));
return { path: dest, size };
}
import { fileTypeFromBuffer } from "file-type";
const ALLOWED = new Set(["image/png", "image/jpeg", "image/webp", "application/pdf"]);
const MAX_BYTES = 100 * 1024 * 1024; // 100 MB
async function validateType(head: Buffer) {
const type = await fileTypeFromBuffer(head);
if (!type || !ALLOWED.has(type.mime)) throw new UploadError(415, "unsupported file type");
return type.mime;
}
// Server: accept one chunk, append to the partial file.
router.put("/uploads/:id/chunks/:index", rawBody({ limit: CHUNK_BYTES }), async (req, res) => {
const { id, index } = req.params;
const session = await uploads.get(id);
if (!session) return res.status(404).end();
if (req.body.length > CHUNK_BYTES) return res.status(413).end();
// Append at the expected offset; reject out-of-order or duplicate chunks.
const offset = Number(index) * CHUNK_BYTES;
await appendFile(session.partialPath, req.body, offset);
await uploads.markChunk(id, Number(index));
res.json({ received: Number(index), complete: session.isComplete() });
});
// Client: resume by asking which chunks the server already has.
async function resumeUpload(id: string, file: File) {
const { chunks } = await fetch(`/uploads/${id}/status`).then(r => r.json());
const total = Math.ceil(file.size / CHUNK_BYTES);
for (let i = 0; i < total; i++) {
if (chunks.includes(i)) continue; // already have it — skip
const blob = file.slice(i * CHUNK_BYTES, Math.min((i + 1) * CHUNK_BYTES, file.size));
await fetch(`/uploads/${id}/chunks/${i}`, { method: "PUT", body: blob });
}
await fetch(`/uploads/${id}/complete`, { method: "POST" });
}
async function completeUpload(id: string) {
const session = await uploads.get(id);
if (!session.isComplete()) throw new Error("incomplete");
const staged = await moveToQuarantine(session.partialPath); // not yet user-visible
await scanQueue.add({ fileId: id, path: staged }); // async job
return { status: "processing", fileId: id };
}
// Worker
scanQueue.process(async (job) => {
const { fileId, path } = job.data;
const clean = await clamav.scan(path); // clamdscan, or an external scanner
if (clean) {
await moveToStorage(path, fileId); // now user-visible
await uploads.setStatus(fileId, "ready");
} else {
await moveToQuarantineVault(path, fileId); // isolated, never visible
await uploads.setStatus(fileId, "rejected");
await audit.log({ fileId, reason: "malware detected" });
}
});
// API: issue a presigned URL for the browser to upload directly to S3.
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
router.post("/uploads/sign", async (req, res) => {
const { filename, contentType, size } = req.body;
if (size > MAX_BYTES) return res.status(413).end();
if (!ALLOWED.has(contentType)) return res.status(415).end();
const key = `${req.user.id}/${crypto.randomUUID()}/${filename}`;
const url = await getSignedUrl(s3, new PutObjectCommand({ Bucket: "uploads", Key: key, ContentType: contentType }), { expiresIn: 300 });
res.json({ uploadUrl: url, key, expiresIn: 300 });
});
// Client: upload directly to S3, then notify the API.
async function uploadDirect(file: File) {
const { uploadUrl, key } = await fetch("/uploads/sign", { method: "POST", body: JSON.stringify({ filename: file.name, contentType: file.type, size: file.size }) }).then(r => r.json());
await fetch(uploadUrl, { method: "PUT", body: file, headers: { "Content-Type": file.type } });
await fetch("/uploads/complete", { method: "POST", body: JSON.stringify({ key }) });
}
function uploadWithProgress(file: File, onProgress: (pct: number) => void): Promise<void> {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.upload.onprogress = (e) => { if (e.lengthComputable) onProgress(e.loaded / e.total); };
xhr.onload = () => xhr.status < 400 ? resolve() : reject(new Error(`HTTP ${xhr.status}`));
xhr.open("PUT", uploadUrl); xhr.send(file);
});
}