欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 名人名企 > Node.js实现文件上传下载

Node.js实现文件上传下载

2024/10/25 4:04:39 来源:https://blog.csdn.net/y523648/article/details/143215146  浏览:    关键词:Node.js实现文件上传下载

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/{想下载的文件名}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com