How*_*ild 6 javascript http node.js
我尝试创建一个服务器,它可以从 HTTP 请求接收文件。我使用 Postman 作为用户代理,并向请求添加一个文件。这是请求:
POST /getfile HTTP/1.1
Host: localhost:3000
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
Cache-Control: no-cache
Postman-Token: 9476dbcc-988d-c9bd-0f49-b5a3ceb95b85
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="file"; filename="test.xls"
Content-Type: application/vnd.ms-excel
------WebKitFormBoundary7MA4YWxkTrZu0gW--
Run Code Online (Sandbox Code Playgroud)
但是当请求到达服务器时,我在其中找不到文件(我的意思是在请求中)。我试图从请求的正文部分接收它,但它返回了 > {}<。我试图弄清楚,如何引用文件名,但不幸的是我在请求头中找不到文件名的任何引用......
谁能帮我查一下,我该怎么办?
作为我评论的后续,您可以使用 multer 模块实现您想要的东西:https ://www.npmjs.com/package/multer
const express = require('express');
const multer = require('multer');
const app = express();
const upload = multer();
app.post('/profile', upload.array(), function (req, res, next) {
// req.body contains the text fields
});
Run Code Online (Sandbox Code Playgroud)
小智 6
您需要解析请求中的表单数据。有几个包可以解决这个问题,特别是formidable、busboy(或busboy-connect)parted和flow。
这是一个使用formidable 的解决方案,它是我处理图像上传等问题的首选解决方案,因为它保存到磁盘。如果您只想读取该文件,可以使用上面的其他包之一。
安装强大
npm install formidable --save
然后,在您的服务器中,您必须解析来自客户端的数据:
// Somewhere at the start of your file
var IncomingForm = require('formidable').IncomingForm
// ...
// Then in your request handler
var form = new IncomingForm()
form.uploadDir = 'uploads'
form.parse(request, function(err, fields, files) {
if (err) {
console.log('some error', err)
} else if (!files.file) {
console.log('no file received')
} else {
var file = files.file
console.log('saved file to', file.path)
console.log('original name', file.name)
console.log('type', file.type)
console.log('size', file.size)
}
})
Run Code Online (Sandbox Code Playgroud)
有几点需要注意:
fs它来重命名或移动它们form.keepExtensions = true是否希望保存的文件保留其扩展名小智 5
var app = require('express')();
var multer = require('multer');
var upload = multer();
app.post('/your_path', upload.array(), function (req, res, next) {
// req.files is array of uploaded files
// req.body will contain the text fields, if there were any
});Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23649 次 |
| 最近记录: |