![](/img/trans.png)
[英]How to send objects from server to client side components in react-express node app
[英]How to retrieve file on server side send with ajax for a node/express app
我有一個 Node/Express 應用程序,我想發送一個帶有表單的文件,我想用 ajax 發送它,以便我可以處理服務器響應。
到目前為止,我的表格是:
<form method='POST' enctype='multipart/form-data' id='excelform'>
<input type='file' id='target_file' name='target_file' required>
</form>
<button class='btn btn-menu3 align-self-end' onClick='excel_email9f();'>Enviar</button>
我有一個按鈕,它為 ajax 請求調用以下函數:
function excel_email9f(){
var data = new FormData();
var file = $('#target_file')[0].files[0];
data.append('file', file);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "/Excelemail9f",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
var response = data.q0;
alert(response);
},
error: function (e) {
console.log("ERROR : ", e);
}
});
};
我可以訪問該文件及其名稱等屬性。
在服務器端,我有這條路線
app.post('/Excelemail9f',function(req,res){
// checking req.files is empty or not
if (Object.keys(req.files).length == 0) {
return res.status(400).send('No files were uploaded.');
}
console.log('name: ' + req.files.target_file.name);
let target_file = req.files.target_file;
// target_file.mv(path, callback)
target_file.mv(path.join(__dirname, 'uploads', target_file.name), (err) => {
if (err) throw err;
res.send(JSON.stringify({q0 : 0}));
})
})
我如何訪問服務器端的文件,我使用req.files.target_file
但我收到以下錯誤:
類型錯誤:無法讀取未定義的屬性“名稱”
你post
荷蘭國際集團的數據作為FormData
對象,但你指的是作為文件名的HTML輸入元素的ID。 您可以通過調用data.append('file', file);
填充FormData
對象data.append('file', file);
,所以你需要通過req.files.file
而不是req.files.target_file
來引用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.