推荐答案
// www.javascriptcn.com code example
const http = require('http');
const fs = require('fs');
const path = require('path');
const server = http.createServer((req, res) => {
if (req.method === 'POST' && req.url === '/upload') {
let body = '';
req.on('data', (chunk) => {
body += chunk;
});
req.on('end', () => {
const filePath = path.join(__dirname, 'uploaded-file.txt');
fs.writeFile(filePath, body, (err) => {
if (err) {
res.statusCode = 500;
res.end('Internal Server Error');
} else {
res.statusCode = 200;
res.end('File uploaded successfully');
}
});
});
} else {
res.statusCode = 404;
res.end('Not Found');
}
});
server.listen(3000, () => {
console.log('Server is running on port 3000');
});本题详细解读
1. 创建HTTP服务器
首先,我们使用 http.createServer() 方法创建一个HTTP服务器。这个方法接受一个回调函数作为参数,该回调函数会在每次有请求到达时被调用。
2. 处理POST请求
在回调函数中,我们检查请求的方法是否为 POST,并且请求的URL是否为 /upload。如果是,则开始处理文件上传。
3. 接收数据
我们通过监听 req 对象的 data 事件来接收上传的数据。每次接收到数据块时,将其追加到 body 变量中。
4. 数据接收完成
当 end 事件触发时,表示数据接收完成。此时,我们将接收到的数据写入到服务器上的一个文件中。
5. 文件写入
使用 fs.writeFile() 方法将接收到的数据写入到指定的文件路径中。如果写入成功,返回200状态码和成功消息;如果写入失败,返回500状态码和错误消息。
6. 处理其他请求
如果请求的方法不是 POST 或者URL不是 /upload,则返回404状态码和“Not Found”消息。
7. 启动服务器
最后,使用 server.listen() 方法启动服务器,监听3000端口。
注意事项
- 这个示例仅适用于小文件上传,因为大文件上传可能会导致内存问题。
- 实际应用中,建议使用
multipart/form-data格式来处理文件上传,并使用第三方库如multer来简化处理流程。 - 安全性方面,需要对上传的文件进行严格的验证和过滤,以防止恶意文件上传。