【问题标题】:Uploading files to backend server on a POST request through Multer, Node and Express通过 Multer、Node 和 Express 在 POST 请求中将文件上传到后端服务器
【发布时间】:2021-08-14 20:59:09
【问题描述】:

我正在尝试通过 POST 请求从我的本地系统向后端服务器发送一个,但我无法每次使用 --binary-data 而不是使用 --form 时都这样做。

这是我想使用 Node.js 构建的示例 curl:

curl --location --request POST 'some-endpoint' \
--form 'file=@"/Users/name/Desktop/sample.csv"'

这是component.html:

<form (ngSubmit)="handleCsvClick()" encrypt="multipart/form-data">
 <input
  type="file"
  name="file-input"
  #fileInput
  [disabled]="requestInProgess"
  (change)="handleFilePick()"
/>
<button
class="upload-btn btn-reset"
type="submit"
>
Upload CSV File
</button>
</form>

这是component.ts:

 handleCsvClick(){
    const file = this.fileInputRef.nativeElement.files[0];
    const form = new FormData();
    form.append("file", file);
    const endpoint = `/api/upload-csv`;
    this.http.post(endpoint,form).subscribe((data) => {
      console.log(data);
    });
  }

Node.js

路由器文件:

const path = require('path');
const express = require("express");
const cookieParser = require("cookie-parser");
const multer = require('multer');
const router = express.Router();
const uuidv4 = require('uuid/v4');
const advisoryController = require("../controllers/advisoryController");
const { UPLOADS_PATH } = require('../config/environment');
const storage = multer.diskStorage({
  destination: UPLOADS_PATH,
  filename: function(_, file, cb) {
    const fileExt = path.extname(file.originalname);
    cb(null, `_csvUploadFile_${uuidv4()}${fileExt}`);
  },
});
const upload = multer({ storage });

router.post("/upload-csv", upload.single("file"), (req, res) => {
  advisoryController
    .uploadCSV(req.file)
    .then(response => res.send(response.data))
    .catch(error => {
      res.status(error.status || 500).send("Something went wrong");
      console.log(error);
    });
});

控制器:

const axios = require("axios");
const { advisoryList } = require("../config/apiConfig");
const fs = require('fs');
const request = require('request');
const FormData = require('form-data');

function uploadCSV(file) {
  let requestUrl = advisoryList.uploadCSV.url;
  const { path } = file;
  const fileUpload = fs.createReadStream(path);
  return new Promise((resolve, reject) => {
    axios
    .post(requestUrl, fileUpload, {headers: {
      'Content-Type': 'multipart/form-data'
    }})
    .then(response => {
      resolve(response.data);
    })
    .catch(error => {
      reject(error)
      console.log("CURL: ", error.request.toCurl());
    });
  })
}

在这一切之后构建的 curl 是以 --data-binary 而不是 --form 的形式出现的:

curl 'someendpoint' -H 'accept: application/json, text/plain, */*' -H 'content-type: multipart/form-data' -H 'user-agent: axios/0.18.0' --data-binary $'userId,name,age,city\n29298914,vish,30,Bangalore\r\n0\r\n\r\n' --compressed

代替:

curl --location --request POST 'some-endpoint' \
--form 'file=@"/Users/name/Desktop/sample.csv"'

任何帮助将不胜感激。提前致谢。

【问题讨论】:

    标签: node.js angular express multipartform-data multer


    【解决方案1】:

    要在 Node.js 中使用 axios 发送文件,您需要:

    1. 使用form-data库创建表单
    2. 使用getHeaders() 设置表单中的请求标头

    将您的代码更改为:

    const form = new FormData();
    form.append('file', fileUpload, path); // 3rd argument is the file name
    
    // Send other fields along with the file
    form.append('title', 'Q1 2021');
    form.append('description', 'An utterly interesting report');
    
    // Get form headers to pass on to axios
    const formHeaders = form.getHeaders();
    
    // Sending a file with axios
    axios.post(requestUrl, form, { headers: { ...formHeaders } });
    

    您的问题启发了我将这个答案写成一篇文章 — Send a File With Axios in Node.js。它涵盖了一些常见的陷阱,您将学习如何发送存储为 Buffer 或来自 Stream 的文件。

    【讨论】:

    • 你是救世主,非常感谢。最后一个问题,如果我想随文件一起发送多个字段,那么理想的方式应该是什么?
    • 不客气!我已经编辑了答案,以向您展示如何发送其他字段。
    • @Vish 你的问题启发了我写一篇关于这个的文章——Sending a File With Axios in Node.js。它涵盖了一些常见的陷阱并将文件作为缓冲区或流发送。谢谢你的启发!
    • 干得好,感谢您为社区做出的贡献。总有一天它肯定会对某人有所帮助。
    猜你喜欢
    • 2020-10-10
    • 2017-03-01
    • 2018-04-23
    • 1970-01-01
    • 2014-11-19
    • 1970-01-01
    • 2023-03-26
    • 2011-09-23
    • 2020-10-18
    相关资源
    最近更新 更多