node上传文件到服务器
时间: 2023-08-26 09:05:38 浏览: 48
要在Node.js中上传文件到服务器,可以使用Node.js的内置模块`fs`和第三方模块`formidable`。
以下是一个简单的例子:
```javascript
const http = require('http');
const formidable = require('formidable');
const fs = require('fs');
http.createServer((req, res) => {
if (req.url === '/upload' && req.method.toLowerCase() === 'post') {
const form = formidable({ multiples: true });
form.parse(req, (err, fields, files) => {
if (err) {
console.error(err);
return;
}
const { path, name, type } = files.file;
const newPath = __dirname + '/' + name;
fs.rename(path, newPath, (err) => {
if (err) {
console.error(err);
return;
}
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('File uploaded and moved!');
res.end();
});
});
return;
}
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(`
<form action="/upload" enctype="multipart/form-data" method="post">
<input type="file" name="file" multiple><br>
<input type="submit" value="Upload">
</form>
`);
}).listen(3000, () => {
console.log('Server listening on http://localhost:3000 ...');
});
```
在代码中,我们首先引入了`http`、`formidable`和`fs`模块。然后创建了一个HTTP服务器,并在服务器中创建了一个上传文件的路由`/upload`。
当用户在表单中选择一个文件并提交表单时,服务器会使用`formidable`模块解析请求,并在回调函数中处理上传的文件。在回调函数中,我们首先获取文件的`path`、`name`和`type`属性,然后将文件移动到服务器上的一个新路径,并在响应中发送一个成功消息。
如果用户没有提交表单,服务器将返回一个包含文件上传表单的HTML页面。
以上是一个简单的例子,你可以根据实际需求进行修改。