nodejs接收multipart/form-data,不使用第三方库,使用注释
时间: 2025-01-19 21:10:53 AIGC 浏览: 87
在Node.js中接收multipart/form-data数据而不使用第三方库,可以通过解析原始的HTTP请求来实现。以下是一个示例代码,展示了如何使用Node.js的内置模块来接收和处理multipart/form-data数据,并附有详细注释:
```javascript
const http = require('http');
const querystring = require('querystring');
const fs = require('fs');
const path = require('path');
http.createServer((req, res) => {
if (req.method === 'POST') {
// 检查是否为multipart/form-data请求
const contentType = req.headers['content-type'];
if (contentType && contentType.indexOf('multipart/form-data') !== -1) {
const boundary = contentType.split('; ')[1].split('=')[1];
let body = '';
req.on('data', chunk => {
body += chunk;
});
req.on('end', () => {
// 分割body为不同的部分
const parts = body.split(new RegExp(`--${boundary}(--)?\r\n`));
const formData = {};
parts.forEach(part => {
if (part) {
// 分割头部和数据
const [header, ...data] = part.split('\r\n\r\n');
const contentDisposition = header.match(/Content-Disposition: form-data; name="([^"]+)"/);
if (contentDisposition) {
const name = contentDisposition[1];
const value = data.join('').replace(/\r\n$/, '');
formData[name] = value;
} else {
// 处理文件上传
const fileMatch = header.match(/Content-Disposition: form-data; name="([^"]+)"; filename="([^"]+)"/);
if (fileMatch) {
const fileName = fileMatch[2];
const fileData = data.join('').replace(/\r\n$/, '');
const filePath = path.join(__dirname, 'uploads', fileName);
fs.writeFile(filePath, fileData, err => {
if (err) {
console.error('文件写入失败:', err);
}
});
}
}
}
});
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(formData));
});
} else {
res.writeHead(400, {'Content-Type': 'text/plain'});
res.end('Invalid content type');
}
} else {
res.writeHead(405, {'Content-Type': 'text/plain'});
res.end('Method not allowed');
}
}).listen(3000, () => {
console.log('服务器正在监听端口3000');
});
```
### 代码说明:
1. **导入模块**:引入`http`, `querystring`, `fs`, 和 `path`模块。
2. **创建服务器**:使用`http.createServer`创建一个服务器,并处理POST请求。
3. **检查Content-Type**:检查请求的`Content-Type`是否为`multipart/form-data`。
4. **解析边界**:从`Content-Type`头中提取`boundary`。
5. **接收数据**:使用`req.on('data')`事件接收数据,并将其存储在`body`变量中。
6. **解析数据**:使用`req.on('end')`事件解析接收到的数据。
7. **分割数据**:将`body`按`boundary`分割成不同的部分。
8. **处理表单数据**:遍历每个部分,解析头部信息,并处理表单数据和文件上传。
9. **响应请求**:将处理后的数据以JSON格式返回给客户端。
阅读全文
相关推荐












