文件上传
- 作者仓库星标 0
- 作者仓库 skills-registry
- 领域
- 通用
- 作者声明的智能体
- 未找到明确声明;不据此推断已兼容或已测试
- 静态检查
- 88 / 100 · 启发式扫描,不代表运行安全
- 运行环境证据
- 未执行;当前没有隔离运行测试证据
- 作者 / 版本 / 许可证
- @tomevault-io · 未声明许可证
- 上下文用量评级
- 低消耗
- 接入复杂程度
- 需简单配置
- 是否需要外部接口密钥
- 不需要
- 兼容的系统
- macOS · Linux · Windows
- 运行环境要求
- Node.js · Python
- 检测到的文件与系统行为
-
- 只读
- 允许写入 / 修改
- 网络行为
- 仅限本地
- 安装命令数
- 无(仅作为资料)
需要注意: 未声明工具权限范围;实际权限由运行环境决定。
# File Upload Handling
## Node.js (Multer — recommended)
```typescript
import multer from 'multer';
import path from 'path';
import crypto from 'crypto';
// Storage configuration
const storage = multer.diskStorage({
destination: './uploads',
filename: (req, file, cb) => {
const uniqueName = `${crypto.randomUUID()}${path.extname(file.originalname)}`;
cb(null, uniqueName);
},
});
// File filter
const fileFilter = (req: Express.Request, file: Express.Multer.File, cb: multer.FileFilterCallback) => {
const allowedMimes = ['image/jpeg', 'image/png', 'image/webp', 'application/pdf'];
if (allowedMimes.includes(file.mimetype)) {
cb(null, true);
} else {
cb(new Error(`File type ${file.mimetype} not allowed`));
}
};
const upload = multer({
storage,
fileFilter,
limits: { fileSize: 10 * 1024 * 1024 }, // 10MB
});
// Single file
app.post('/upload', upload.single('file'), (req, res) => {
res.json({ filename: req.file!.filename, size: req.file!.size });
});
// Multiple files
app.post('/upload/multiple', upload.array('files', 10), (req, res) => {
res.json({ count: (req.files as Express.Multer.File[]).length });
});
// Error handling
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
if (err instanceof multer.MulterError) {
if (err.code === 'LIMIT_FILE_SIZE') return res.status(413).json({ error: 'File too large' });
return res.status(400).json({ error: err.message });
}
if (err.message.includes('not allowed')) return res.status(415).json({ error: err.message });
next(err);
});
```
### Memory storage (for cloud forwarding)
```typescript
const upload = multer({ storage: multer.memoryStorage(), limits: { fileSize: 10 * 1024 * 1024 } });
app.post('/upload', upload.single('file'), async (req, res) => {
// req.file.buffer contains the file — forward to S3
await s3.send(new PutObjectCommand({
Bucket: bucket, Key: key, Body: req.file!.buffer, ContentType: req.file!.mimetype,
}));
});
```
## Python (FastAPI)
```python
from fastapi import UploadFile, File, HTTPException
import aiofiles, uuid
ALLOWED_TYPES = {"image/jpeg", "image/png", "application/pdf"}
MAX_SIZE = 10 * 1024 * 1024 # 10MB
@app.post("/upload")
async def upload_file(file: UploadFile = File(...)):
if file.content_type not in ALLOWED_TYPES:
raise HTTPException(415, f"Type {file.content_type} not allowed")
content = await file.read()
if len(content) > MAX_SIZE:
raise HTTPException(413, "File too large")
filename = f"{uuid.uuid4()}{Path(file.filename).suffix}"
async with aiofiles.open(f"uploads/{filename}", "wb") as f:
await f.write(content)
return {"filename": filename, "size": len(content)}
```
## Java (Spring Boot)
```java
@PostMapping("/upload")
public ResponseEntity<Map<String, String>> upload(
@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) throw new ResponseStatusException(BAD_REQUEST, "Empty file");
if (file.getSize() > 10_000_000) throw new ResponseStatusException(PAYLOAD_TOO_LARGE);
String ext = StringUtils.getFilenameExtension(file.getOriginalFilename());
String filename = UUID.randomUUID() + "." + ext;
Path dest = Path.of("uploads", filename);
file.transferTo(dest);
return ResponseEntity.ok(Map.of("filename", filename));
}
```
Spring config:
```yaml
spring:
servlet:
multipart:
max-file-size: 10MB
max-request-size: 10MB
```
## File Validation Beyond MIME
```typescript
// Validate actual file content (magic bytes), not just extension
import { fileTypeFromBuffer } from 'file-type';
const type = await fileTypeFromBuffer(req.file!.buffer);
if (!type || !['image/jpeg', 'image/png'].includes(type.mime)) {
return res.status(415).json({ error: 'Invalid file content' });
}
```
## Anti-Patterns
| Anti-Pattern | Fix |
|--------------|-----|
| Trust client MIME type only | Validate magic bytes with `file-type` |
| Original filename as storage key | Use UUID to prevent path traversal and collisions |
| No file size limit | Always set `limits.fileSize` |
| Sync disk writes on upload | Use streams or async writes |
| Storing uploads in app directory | Use separate `/uploads` or cloud storage |
| No cleanup of temp files | Implement lifecycle/cron cleanup |
## Production Checklist
- [ ] File size limits configured
- [ ] MIME type whitelist (validate magic bytes, not just extension)
- [ ] UUID filenames (never use original filename for storage)
- [ ] Multer error handler middleware
- [ ] Virus scanning for user uploads (ClamAV)
- [ ] Rate limiting on upload endpoints
- [ ] Cleanup strategy for orphaned files
---
> Source: [claude-dev-suite/claude-dev-suite](https://github.com/claude-dev-suite/claude-dev-suite) — distributed by [TomeVault](https://tomevault.io).
<!-- tomevault:4.0:skill_md:2026-05-22 -->
章节与文件索引
按说明文件中的顺序排列。
Java(春季启动)
反模式
生产清单
文件/命令 -> ${crypto.randomUUID()}${path.extname(file.originalname)} · File type ${file.mimetype} not allowed · file-type · limits.fileSize · /uploads
内容校验值 -> 918047b84d12
当前原文的自动摘译,尚未人工审校。
Java(春季启动)
弹簧配置:
反模式
反模式 · 仅修复信任客户端 MIME 类型 · 使用
file-type原始文件名作为存储密钥验证魔字节 · 使用 UUID 防止路径遍历和冲突 无文件大小限制 · 始终设置limits.fileSize上传时同步磁盘写入 · 使用流或异步写入生产清单
[ ] 配置文件大小限制 [ ] MIME 类型白名单(验证幻字节,而不仅仅是扩展名) [ ] UUID 文件名(切勿使用原始文件名进行存储) [ ] Multer 错误处理程序中间件 [ ] 对用户上传进行病毒扫描 (ClamAV)