nodejs实现txt文件上传下载
时间: 2023-11-16 17:00:49 浏览: 95
Node.js实现文件上传
以下是使用Node.js实现txt文件上传和下载的代码示例:
上传文件:
```javascript
const http = require('http');
const fs = require('fs');
const server = http.createServer((req, res) => {
if (req.method === 'POST') {
const fileStream = fs.createWriteStream('file.txt');
req.pipe(fileStream);
req.on('end', () => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('File uploaded successfully!');
});
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(`
<form action="/" method="post" enctype="multipart/form-data">
<input type="file" name="file" /><br /><br />
<input type="submit" value="Upload" />
</form>
`);
}
});
server.listen(8080, () => {
console.log('Server is running on port 8080');
});
```
下载文件:
```javascript
const http = require('http');
const fs = require('fs');
const server = http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/download') {
const fileStream = fs.createReadStream('file.txt');
res.writeHead(200, {
'Content-Type': 'application/octet-stream',
'Content-Disposition': 'attachment; filename=file.txt',
});
fileStream.pipe(res);
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(`
<a href="/download">Download file</a>
`);
}
});
server.listen(8080, () => {
console.log('Server is running on port 8080');
});
```
阅读全文