节点js在HTTP请求中接收文件

我尝试创build一个服务器,什么可以从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-- 

但是,当请求到达服务器,我无法find它的文件(我的意思是在请求)。 我试图从请求的正文部分接收它,但它返回> {} <。 我试图弄清楚,我怎样才能引用文件的名称,但不幸的是我找不到任何引用在文件名称的请求头…

有谁能帮我弄清楚,我该怎么办?

作为我的评论的后续,你可以使用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 }); 
 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 }); 

您需要parsing请求中的表单数据。 有几个软件包可以解决这个问题,特别是formidablebusboy (或者busboy-connect ), partedflow

这是一个使用强大的解决scheme,这是我喜欢的解决scheme,像图片上传,因为它保存到磁盘。 如果你只是想读取文件,你可以使用上面的其他软件包之一。

安装强大

npm install formidable --save

然后,在您的服务器中,您将不得不parsing来自客户端的数据:

 // 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) } }) 

有几件事要注意:

  • 强大的保存新名称的文件,您可以使用fs重命名或移动它们
  • 你可以设置form.keepExtensions = true如果你想保存的文件保持其扩展名