1. 安装 express, multer库
npm install express multer
2. upload.js
import multer from 'multer';
import path from 'path';
// 设置 multer 存储配置
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/'); // 上传的目录,如果不存在会报错
},
filename: (req, file, cb) => {
cb(null, Date.now() + path.extname(file.originalname)); // 用时间重命名文件
}
});
// 创建 multer 实例
const upload = multer({ storage: storage });
//异步方法 (可选)
async function uploadFile(req, res) {
return await new Promise((resolve, reject) => {
upload.single('file')(req, res, (err) => {
if (err) {
reject(err);
} else {
resolve('文件上传成功!');
}
});
});
}
export default upload
export { uploadFile }
3. index,js
import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
// 获取当前文件的目录 ES6的写法,如果是CommonJS,可以直接使用__filename和__dirname
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
import upload, {uploadFile} from './upload.js'
const app = express();
const port = 3000;
app.use(express.json())
//这里分别展示同步和异步处理,像文件上传这种可能比较耗时的操作,建议用异步,这样不会造成服务器阻塞
// 异步处理上传请求
app.post('/upload', (req, res) => {
uploadFile(req, res).then((data) => {
res.json({ success: true, message: data });
}).catch((err) => {
res.status(500).json({ success: false, message: err.message });
});
});
//同步处理上传请求
/*
app.post('/upload', upload.single('file'), (req, res) => {
res.json({ success: true, message: '文件上传成功!' });
});
*/
app.get('/download/:filename', (req, res) => {
const file = path.join(__dirname, 'uploads', req.params.filename); // 指定下载文件的路径
console.info(file);
res.download(file, err => {
console.info(err);
if (err) {
res.status(404).send('文件未找到!');
}
});
});
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});
4. 前端页面upload.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文件上传</title>
</head>
<body>
<h1>上传文件</h1>
<form action="http://localhost:3000/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file" required>
<button type="submit">上传</button>
</form>
</body>
</html>
5.运行服务器
node index.js
7. 运行前端页面执行上传
8. 下载用浏览器访问:
http://localhost:3000/download/{想下载的文件名}