[英]Where should be located a database config file in Node.js and Express?
[英]Where would a file be located on my Node.js + Express server if I send a CSV file to the server using jQuery's ajax method?
我正在使用 jQuery 的 ajax POST 方法向我的節點 + 快遞服務器發送一個 CSV 文件。 當我將 csv 文件發布到我的快遞路線時,我不知道一旦它到達服務器,如何訪問該文件。 我的目標是將 CSV 文件傳遞到名為 upload.single() 的路由中間件中。 我也不確定要為 ajax 調用指定哪種數據類型。
這是我接受 CSV 文件的表單:
<form onSubmit={this.handleSubmit.bind(this)} encType="multipart/form-data">
<input id="userFile" type="file" name="userFile"></input>
<input type="submit" name="submit" value="Upload New Candidates"></input>
</form>
這是我的 handleSubmit 函數,它發出 POST 請求:
handleSubmit(event) {
event.preventDefault();
var csvToSend = document.getElementById("userFile").files[0];
$.ajax({
type: "POST",
url: 'http://localhost:3000/',
data: csvToSend,
success: success,
dataType: //not sure what to put here
});
}
這是我在服務器上的快速路線。 我應該如何訪問從客戶端發送的 CSV 文件並將其輸入到 upload.single() 中間件中?
app.post('/', upload.single('userFile'), function(req, res, next) {
res.sendStatus(200);
});
正如 peteb 提到的,您似乎對單個文件使用了 multer,因此在這種情況下:
// If you set up multer to store files locally
const upload = multer({ dest: 'uploads/' });
const fs = require("fs");
app.post('/', upload.single('userFile'), async function(req, res, next) {
const filePath = req.file.path;
const fileData = await fs.promises.readFile(filePath); // Buffer of csv file
const csvString = fileData.toString();
// Do whatever you need to with the csv file
res.sendStatus(200);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.