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

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)

但是当请求到达服务器时,我在其中找不到文件(我的意思是在请求中)。我试图从请求的正文部分接收它,但它返回了 > {}<。我试图弄清楚,如何引用文件名,但不幸的是我在请求头中找不到文件名的任何引用......

谁能帮我查一下,我该怎么办?

sta*_*kas 7

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

  • 有没有办法在不使用任何第三方模块的情况下接收文件? (14认同)

小智 6

您需要解析请求中的表单数据。有几个包可以解决这个问题,特别是formidablebusboy(或busboy-connectpartedflow

这是一个使用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)