Search code examples
expressuploadpugmulter

node express multer fast-csv pug file upload


I trying to upload a file using pug, multer and express.

The pug form looks like this

form(method='POST' enctype="multipart/form-data")
    div.form-group
    input#uploaddata.form-control(type='file', name='uploaddata' )
    br
    button.btn.btn-primary(type='submit' name='uploaddata') Upload

The server code looks like this (taken out of context)

.post('/uploaddata', function(req, res, next) {
    upload.single('uploaddata',function(err) {
    if(err){
      throw err;
      } else {
    res.json({success : "File upload sucessfully.", status : 200});
    }
  });
})

My issue is that while the file uploads successfully, the success message is not shown on the same page, ie: a new page is loaded showing

{success : "File upload sucessfully.", status : 200}

As an example for other elements (link clicks) the message is displayed via such javascript:

$("#importdata").on('click', function(){
        $.get( "/import", function( data ) {
            $("#message").show().html(data['success']);
        });
    });

I tried doing a pure javascript in order to workaround the default form behaviour but no luck.


Solution

  • Your issue has to do with mixing form submissions and AJAX concepts. To be specific, you are submitting a form then returning a value appropriate to an AJAX API. You need to choose one or the other for this to work properly.

    If you choose to submit this as a form you can't use res.json, you need to switch to res.render or res.redirect instead to render the page again. You are seeing exactly what you are telling node/express to do with res.json - JSON output. Rendering or redirecting is what you want to do here.

    Here is the MDN primer on forms and also a tutorial specific to express.js.

    Alternatively, if you choose to handle this with an AJAX API, you need to use jquery, fetch, axios, or similar in the browser to send the request and handle the response. This won't cause the page to reload, but you do need to handle the response somehow and modify the page, otherwise the user will just sit there wondering what has happened.

    MDN has a great primer on AJAX that will help you get started there. If you are going down this path also make sure you read up on restful API design.

    Neither one is inherently a better strategy, both methods are used in large-scale production applications. However, you do need to choose one or the other and not mix them as you have above.