Raven Dreamer
Raven Dreamer

Reputation: 7160

How do I POST a file submission with jquery?

I have a very simple webpage that allows users to select a file from their OS and 'Submit' to a server running node.js.

I am now in the process of updating the frontend to use jQuery so that I can keep the user on the same page, and then do something useful with the server's response.

I have added jQuery code as per this answer here, but doing so has altered the server's ability to actually find (and use) the passed file.

Is there something specific I need to add in when POSTing files?

Relevant HTML:

<form id="upload" enctype="multipart/form-data" 
  action="http://localhost:3000/file_upload" method ="post">
        <div>
            <label for="pickedFile">Upload CSV: </label><input type="file" name="pickedfile" id = "pickedfile"/>
        </div>

        <div>
            <button>Send the file</button>
        </div>
</form>
<script src="js/app.js"></script>

Relevant app.js snippet is as follows:

// site/js/app.js

var app = app || {};

(function($){


})(jQuery);

$(function(){
  $("form").submit(function(){
    $.post($(this).attr("action"), $(this).serialize(), function(jsonData){
      console.log(jsonData);
    }, "json");
    return false;
  });
});

Relevant server snippet is as follows:

var app = express();

//need to configure this before setting up the routes
//if you want file passing to work correctly
app.configure(function(){
  app.use(express.bodyParser());
  app.use(app.router);
});
app.post('/file_upload', function(req, res) {
    //file should be in req.files.pickedfile

    // get the temporary location of the file
    // When using jquery, pickedfile is undefined!
    var tmp_path = req.files.pickedfile.path;
 });

Upvotes: 0

Views: 107

Answers (1)

gustavohenke
gustavohenke

Reputation: 41440

Your Express part seems to be just fine, however the jQuery code would need a plugin like jQuery.Form, which handles multipart form submission:

$("form").ajaxForm({
  data: {
    extraParam: "foobar"
  },
  error: function() {
    alert("Uh oh, something went wrong");
  },
  success: function( response ) {
    alert("Upload completed!");
    console.log( response );
  }
});

Upvotes: 1

Related Questions