You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
2.3 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
// 创建 Express 应用实例
const app = express();
const PORT = 3000; // 可以根据需要修改端口
// 设置文件上传目录
const uploadDir = 'uploads/';
// 检查 uploads 目录是否存在如果不存在则创建它
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir, { recursive: true });
}
// 设置文件存储配置
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, uploadDir); // 指定文件上传目录
},
filename: (req, file, cb) => {
// 使用当前时间戳和原文件名生成唯一文件名
cb(null, Date.now() + path.extname(file.originalname));
}
});
// 创建上传实例并添加文件过滤和大小限制
const upload = multer({
storage,
limits: { fileSize: 5 * 1024 * 1024 }, // 限制文件大小为 5MB
fileFilter: (req, file, cb) => {
const filetypes = /jpeg|jpg|png|gif|pdf/;
const mimetype = filetypes.test(file.mimetype);
const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
if (mimetype && extname) {
return cb(null, true);
}
cb(new Error('只允许上传 JPEG、PNG、GIF 和 PDF 文件'));
}
});
// 中间件用于解析 JSON URL 编码的数据
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// 提供静态文件服务仅允许访问 uploads 目录
app.use('/uploads', express.static(uploadDir));
// 定义文件上传接口
app.post('/api/upload-file', upload.single('file'), (req, res) => {
if (!req.file) {
return res.status(400).json({ message: '没有文件上传' });
}
res.status(200).json({ message: '文件上传成功', filename: req.file.filename });
});
// 错误处理
app.use((err, req, res, next) => {
if (err instanceof multer.MulterError) {
return res.status(400).json({ message: err.message });
} else if (err) {
console.error(err.stack);
return res.status(500).json({ message: '服务器内部错误' });
}
next();
});
// 启动服务器
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});