How to send a file to Nodejs using FormData and have Node send back a confirmation message?

18,225

Solution 1

HERE'S THE BEST SOLUTION to this question -> Credit goes to: https://codeforgeek.com/2014/11/ajax-file-upload-node-js/

HTML

 <html>
 <head>
 <title>File upload Node.</title>
 </head>
 <body>
  <form id="uploadForm"
      enctype="multipart/form-data"
      action="/api/photo"
      method="post">
  <input type="file" name="userPhoto" />
  <input type="submit" value="Upload Image" name="submit">
  <span id = "status"></span>
 </form>
 </body>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
 <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/jquery.form.min.js"></script>
<script>
$(document).ready(function() {

 $('#uploadForm').submit(function() {
     $("#status").empty().text("File is uploading...");

    $(this).ajaxSubmit({

        error: function(xhr) {
                status('Error: ' + xhr.status);
        },

        success: function(response) {
                console.log(response)
                $("#status").empty().text(response);
        }
   });

  return false;
  });    
});
</script>
</html>

SERVER

var express         =       require("express");
var multer          =       require('multer');
var app             =       express();
var upload          =       multer({ dest: './uploads/'});

app.use(multer({ dest: './uploads/',
rename: function (fieldname, filename) {
    return filename+Date.now();
},
onFileUploadStart: function (file) {
    console.log(file.originalname + ' is starting ...');
},
onFileUploadComplete: function (file) {
    console.log(file.fieldname + ' uploaded to  ' + file.path)
 }
}));

app.get('/',function(req,res){
  res.sendFile(__dirname + "/index.html");
});

app.post('/api/photo',function(req,res){
upload(req,res,function(err) {
    if(err) {
        return res.end("Error uploading file.");
    }
    res.end("File is uploaded");
  });
});

app.listen(3000,function(){
 console.log("Working on port 3000");
});

Solution 2

what about using formidables,

var formidable = require("formidable");

function imageUpload(req,res){

 var form = new formidable.IncomingForm();

 form.parse(req, function (err, fields, files) {


 console.log("imagePath:"+files.filepath.path);
 //assume <input type = "file" name="filepath">
 res.send("file uploaded");
  });

} 
Share:
18,225
HenryDev
Author by

HenryDev

I'm a Full Stack Software Developer. Worked on many Web applications using Javascript, PHP, HTML/CSS, Angular, jQuery, Nodejs, Laravel,etc. Also worked on applications using Java, C/C++, Python, Groovy,etc. "Coding isn't just a job for me, but my biggest passion. If you can think it you can create it!"

Updated on August 21, 2022

Comments

  • HenryDev
    HenryDev over 1 year

    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;
    
  • HenryDev
    HenryDev over 8 years
    you know that JSON cannot have a property that holds a file value right?
  • HenryDev
    HenryDev over 8 years
    how would the html file look like?