通过 Multer、Node 和 Express 根据 POST 请求将文件上传到后端服务器
Uploading files to backend server on a POST request through Multer, Node and Express
我正在尝试通过 POST 请求从我的本地系统发送一个到后端服务器,但我无法每次都使用 --binary-data 而不是使用一个 --form.
这是我想使用 Node.js:
构建的样本卷曲
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 中发送带有 axios 的文件,您需要:
- 使用
form-data
库创建表单
- 从带有
getHeaders()
的表单中设置请求 headers
将您的代码更改为:
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。它涵盖了一些常见的陷阱,您将学习如何发送存储为缓冲区或来自流的文件。
我正在尝试通过 POST 请求从我的本地系统发送一个到后端服务器,但我无法每次都使用 --binary-data 而不是使用一个 --form.
这是我想使用 Node.js:
构建的样本卷曲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 中发送带有 axios 的文件,您需要:
- 使用
form-data
库创建表单 - 从带有
getHeaders()
的表单中设置请求 headers
将您的代码更改为:
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。它涵盖了一些常见的陷阱,您将学习如何发送存储为缓冲区或来自流的文件。