Hi I'm working on this simple form trying to send a file to my Nodejs server using FormData
, but for some reason Node never receives it. Also How can I have Node send back a confirmation message on the page saying that file was received. What is it that I'm doing wrong or missing?. Please help. Thank you in advance. Here's my code.
HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
var fd = new FormData();
fd.append( 'file', input.files[0] );
$.ajax({
url: '/uploadfile',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
</script>
</head>
<body>
<form enctype='multipart/form-data'>
<input type= "text" name = "theName"/>
<input type="file" id="file" name="file">
<input type="submit">
</form>
</body>
</html>
Server (Nodejs)
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res){
res.sendfile('./public/html/form-file.html');
});
/* POST file */
router.post('/', function(req , res){
console.log('Request received: ');
console.log(req.body) // this line helps inspect the request so you can see whether the data is in the url (GET) or the req body (POST)
console.log('\nRequest recieved: \nmethod: ' + req.method + '\nurl: ' + req.url) // this line logs just the method and url
res.end('callback(\'{\"msg\": \"OK\"}\')');
});
module.exports = router;