Reputation: 173
I have a Node/Express app and i want to sent a file with a form, i want to send it with ajax so i can process the server response.
So far my form is:
<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>
i have a button that calls the following function for an ajax request:
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);
}
});
};
i can access the file and its properties like name.
On server side i have this route
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}));
})
})
How do i access the file on the server side, i use req.files.target_file
but i get the following error:
TypeError: Cannot read property 'name' of undefined
Upvotes: 0
Views: 186
Reputation: 11744
You're post
ing the data as a FormData
object, but you're referring to the HTML input element's ID as the filename. You populate the FormData
object by calling data.append('file', file);
, so you need to reference it by req.files.file
rather than req.files.target_file
.
Upvotes: 1