如何在快速POST请求中访问文件内容?

时间:2019-07-17 05:37:50

标签: javascript node.js express

我有一个Express端点,我正在将文件上传到:

app.post('/geocode', function (req, res) {
    console.log('Body',req.body.toString('utf8'))
})

记录:

Body ----------------------------512543447589812896769681
Content-Disposition: form-data; name="file"; filename="test.csv"
Content-Type: text/csv

"10342 Gold Drive, Grass Valley CA 95945"
"135 San Lorenzo Ave #530, Coral Gables, FL 33146"
"2739 Vermont St, Detroit, Michigan"
----------------------------512543447589812896769681--

文件采用名为file的形式数据参数。我正在通过邮递员发出请求,但CURL等效项是:

curl -X POST \
  http://localhost:8080/geocode \
  -H 'Accept: */*' \
  -H 'Cache-Control: no-cache' \
  -H 'Connection: keep-alive' \
  -H 'Content-Type: multipart/form-data' \
  -H 'Host: localhost:8080' \
  -H 'Postman-Token: bfda34b3-df9b-44ba-b7f7-1b268226a848,08558c66-24fa-4d0d-9b70-7bf38cf82399' \
  -H 'User-Agent: PostmanRuntime/7.15.0' \
  -H 'accept-encoding: gzip, deflate' \
  -H 'cache-control: no-cache' \
  -H 'content-length: 333' \
  -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
  -H 'enctype: multipart/form-data' \
  -F file=@Geo-Services/data/test.csv

我想知道的是如何在没有通过HTTP请求附加所有额外内容的情况下访问文件内容?

1 个答案:

答案 0 :(得分:0)

有两种选择。

第一:您可以简单地将csv文件编码为base64,然后像发送字符串一样将其正常发送到服务器。然后,您可以将base64解析为csv。这不是最佳做法,但仍然有用

第二:如我所见,您正在发送multipart/form-data,因此在服务器中,您必须选择该文件,其中有一个最受欢迎的文件包是multer

以下是要点,它是您的快递服务器的非常基本的代码示例

var fs = require('fs');
var express = require('express');
var multer = require('multer');
var csv = require('fast-csv');

var router = express.Router();
var upload = multer({dest: 'tmp/csv/'});

router.post('/upload', upload.single('file'), function (req, res, next) {
  var fileRows = [], fileHeader;

  // open uploaded file
  csv.fromPath(req.file.path)
    .on("data", function (data) {
      fileRows.push(data); // push each row
    })
    .on("end", function () {
      fs.unlinkSync(req.file.path);   // remove temp file
      //process "fileRows"
    }
}

使用的必需软件包

{
  "name": "csvupload",
  "dependencies": {
    "express": "~4.13.1",
    "fast-csv": "^1.0.0",
    "multer": "^1.1.0"
  }
}

,然后在您的前端中发送该文件:

const payload = new FormData();
payload.append('file', csvFile); //csvFile variable holds the file that you've selected.
//Note: Just don't mention the data type that you want to send. you don't need to include anythings like `multipart/form-data` just the method and body is fine.
let options = {
    method: 'POST',
    body: payload
};
let url = `http://uri.com/upload` // 'upload' is the endpoint in this case.
fetch(url, options)
.then(response => response.json())
.then(result => {
  //Here responses will needed to be handled.
})
.catch(err => {
  //catch if there is any error
})