生成一个nodejs web服务器接受用户上传文件并保存(仅使用原生函数 )
- User
生成一个nodejs web服务器接受用户上传文件并保存(仅使用原生函数 )
- Assistant
生成一个nodejs web服务器接受用户上传文件并保存(仅使用原生函数 )
当然,下面是一个使用 Node.js 原生模块(不依赖任何第三方库)搭建的简单 Web 服务器示例。该服务器可以接受用户上传的文件,并将其保存到服务器的指定目录中。
此示例使用了 http 模块创建服务器,fs 模块处理文件系统操作,以及 path 模块处理文件路径。为了简化处理,假设上传的文件是通过 multipart/form-data 编码的表单提交。
注意: 手动解析
multipart/form-data边界和内容是相对复杂且容易出错的。对于生产环境,建议使用成熟的库如multer来处理文件上传。然而,以下示例展示了如何仅使用原生 Node.js 模块实现基本的文件上传功能。
POST 且 Content-Type 为 multipart/form-data。const http = require('http');
const fs = require('fs');
const path = require('path');
// 指定上传文件的保存目录
const uploadDir = path.join(__dirname, 'uploads');
// 确保上传目录存在
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir);
}
const server = http.createServer((req, res) => {
if (req.method.toLowerCase() === 'post') {
const contentType = req.headers['content-type'];
if (contentType && contentType.startsWith('multipart/form-data')) {
// 提取 boundary
const boundary = '--' + contentType.split('boundary=')[1];
let buffer = Buffer.alloc(0);
req.on('data', chunk => {
buffer = Buffer.concat([buffer, chunk]);
});
req.on('end', () => {
// 分割各个部分
const parts = buffer.split(Buffer.from(boundary));
parts.forEach(part => {
// 忽略第一个空部分和最后的 '--' 结束部分
if (part.length === 0 || part.equals(Buffer.from('--\r\n'))) {
return;
}
// 转换为字符串,查找文件名
const headerEnd = part.indexOf('\r\n\r\n');
const header = part.slice(0, headerEnd).toString();
const contentDisposition = header.match(/Content-Disposition: form-data; name="(.+?)"; filename="(.+?)"/);
if (contentDisposition) {
const filename = contentDisposition[2];
const fileData = part.slice(headerEnd + 4, part.length - 2); // 去除结尾的 \r\n
// 定义文件保存路径
const filePath = path.join(uploadDir, path.basename(filename));
// 写入文件
fs.writeFile(filePath, fileData, err => {
if (err) {
console.error('文件保存失败:', err);
res.writeHead(500, {'Content-Type': 'text/plain'});
res.end('文件上传失败');
return;
}
console.log(`文件已保存: ${filePath}`);
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('文件上传成功');
});
}
});
});
} else {
res.writeHead(400, {'Content-Type': 'text/plain'});
res.end('无效的内容类型');
}
} else {
// 提供简单的上传表单
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(`
<h2>上传文件</h2>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="uploadFile" /><br/><br/>
<input type="submit" value="上传" />
</form>
`);
}
});
// 扩展 Buffer 原型以支持分割操作
Buffer.prototype.split = function (delimiter) {
let arr = [];
let start = 0;
let index;
while ((index = this.indexOf(delimiter, start)) !== -1) {
arr.push(this.slice(start, index));
start = index + delimiter.length;
}
arr.push(this.slice(start));
return arr;
};
const PORT = 3000;
server.listen(PORT, () => {
console.log(`服务器正在运行,访问 http://localhost:${PORT} 来上传文件`);
});
创建上传目录:
const uploadDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir);
}
这段代码确保服务器有一个名为 uploads 的目录,用于保存上传的文件。如果该目录不存在,将会创建它。
创建 HTTP 服务器:
const server = http.createServer((req, res) => {
// 请求处理逻辑
});
使用 http.createServer 创建服务器,并定义请求处理逻辑。
处理 POST 请求:
if (req.method.toLowerCase() === 'post') {
// 处理文件上传
}
服务器检查请求方法是否为 POST,通常文件上传会使用 POST 方法。
解析 multipart/form-data:
const contentType = req.headers['content-type'];
if (contentType && contentType.startsWith('multipart/form-data')) {
// 提取边界和处理数据
}
确认请求头中的 Content-Type 为 multipart/form-data,并提取边界(boundary)用于解析数据。
处理数据流:
req.on('data', chunk => {
buffer = Buffer.concat([buffer, chunk]);
});
req.on('end', () => {
// 分割并处理各个部分
});
服务器监听 data 事件,接收数据块并合并到 buffer 中。end 事件触发后,开始解析完整的数据。
解析并保存文件:
const parts = buffer.split(Buffer.from(boundary));
parts.forEach(part => {
// 解析每个部分,提取文件并保存
});
使用自定义的 Buffer.prototype.split 方法将整个请求体按照边界分割成多个部分。对于每个部分,检查是否包含文件,并将文件内容保存到服务器。
提供上传表单:
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(`
<h2>上传文件</h2>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="uploadFile" /><br/><br/>
<input type="submit" value="上传" />
</form>
`);
如果请求方法不是 POST,服务器返回一个简单的 HTML 表单,允许用户选择文件并上传。
扩展 Buffer 原型:
Buffer.prototype.split = function (delimiter) {
// 分割 Buffer 函数实现
};
为 Buffer 对象添加一个 split 方法,用于根据指定的分隔符分割缓冲区。这在解析 multipart/form-data 时非常有用。
server.js。node server.js
服务器将会在端口 3000 上启动,并创建一个 uploads 目录用于保存上传的文件。uploads 目录中。multipart/form-data 可能在处理大型文件或高并发时表现不佳。使用专门的库可以更高效地处理这些情况。希望这个示例对你理解如何使用 Node.js 原生模块处理文件上传有所帮助!
Not yet included in a published release.