node上传文件到服务器
时间: 2023-08-26 14:05:24 浏览: 127
要在Node.js中上传文件到服务器,可以使用Node.js的`formidable`模块。以下是一个简单的例子,演示如何将文件上传到服务器:
首先,需要安装`formidable`模块:
```
npm install formidable
```
然后,在Node.js文件中,需要引入`formidable`模块,并创建一个用于处理文件上传的路由。以下是一个示例代码:
```javascript
const formidable = require('formidable');
const http = require('http');
const fs = require('fs');
http.createServer(function(req, res) {
if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
// 创建一个新的formidable.IncomingForm对象
const form = new formidable.IncomingForm();
// 设置文件上传目录
form.uploadDir = "./upload";
// 保留文件扩展名
form.keepExtensions = true;
// 解析上传的文件
form.parse(req, function(err, fields, files) {
if (err) throw err;
// 将上传的文件从临时目录移动到上传目录
const oldpath = files.file.path;
const newpath = './upload/' + files.file.name;
fs.rename(oldpath, newpath, function(err) {
if (err) throw err;
// 文件上传成功,返回客户端
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('File uploaded!');
res.end();
});
});
} else {
// 显示文件上传表单
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<form action="/upload" method="post" enctype="multipart/form-data">');
res.write('<input type="file" name="file"><br>');
res.write('<input type="submit" value="Upload">');
res.write('</form>');
res.end();
}
}).listen(3000);
```
在上面的代码中,当用户访问`/upload`路由并提交文件上传表单时,`formidable`模块将解析上传的文件并将其移动到指定的上传目录中。
注意,这个例子中的`uploadDir`和`newpath`都是相对路径,如果要使用绝对路径,需要将其改为绝对路径。
希望这能帮助到你!
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044736.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![.zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)