Srijan Sharma
Srijan Sharma

Reputation: 693

Sending formdata for file upload using ajax

I am trying to upload an image by using form data with ajax. Though below line seems to be working fine and saving the image on my local machine.

<form ref='uploadForm' id='uploadForm' action='/tab10/uploadImage' method='post' encType="multipart/form-data">
<input type="file" class="btn btn-default" name="file" />
<input type='submit' class="btn btn-default" value='Broadcast Image' />
</form>

But when instead of specifying action as a form attribute, i try to make the call using ajax, things didn't seem to be working fine.Below is the code that i am using to make the post API call using ajax.

HTML

<form ref='uploadForm' id='uploadForm' encType="multipart/form-data">

Jquery

$("form#uploadForm").submit(function (event) {
          //disable the default form submission
          event.preventDefault();
          var formData = $(this).serialize();
          console.log(formData);
          $.ajax({
              url: '/tab10/uploadImage',
              type: 'POST',
              data: formData,
              async: false,
              cache: false,
              contentType: false,
              processData: false,
              success: function () {
                  alert('Form Submitted!');
              },
              error: function(){
                  alert("error in ajax form submission");
              }
          });
          return false;
      });

Below is the code i am using for saving the image.

exports.uploadImage = function(req, resp) {
var res = {};
let file = req.files.file;
file.mv('./images/image', function(err) {
if (err) {
  res.status = 500;
  res.message = err;
  // return res.status(500).send(err);
  return resp.send(res);
}
res.status = 200;
res.message = 'File uploaded!';
return resp.send(res);
});
};

When i checked the request data in my uploadimage function, it seems that in the request, parameter called "files" is not being send in the later case.

Upvotes: 1

Views: 13150

Answers (3)

OLH
OLH

Reputation: 204

I think you have to create FormData, after you can append the file to the formData, add an ID to the input <input type="file" class="btn btn-default" name="file" id="uploadFile"/>

 $("form#uploadForm").submit(function (event) {
      //disable the default form submission
      event.preventDefault();
      var formData = new FormData();
      formData.append('file',$('#uploadFile')[0].files[0]);
      $.ajax({
          url: '/tab10/uploadImage',
          type: 'POST',
          data: formData,
          contentType: false,
          processData: false,
          success: function () {
              alert('Form Submitted!');
          },
          error: function(){
              alert("error in ajax form submission");
          }
      });

  });

Upvotes: 3

Zigri2612
Zigri2612

Reputation: 2310

Use this format to fire ajax.because file is multipart or jquery serialize() method not serialize multipart content,so we need to put it manual.

//get choosen file
var fileContent = new FormData();
fileContent.append("file",$('input[type=file]')[0].files[0]);
$.ajax({
     type: "POST",
      enctype:"multipart/form-data",
       url: "/tab10/uploadImage",
       data: fileContent,
       processData: false,
       contentType: false,
       success: function(response) {
        }
});

Upvotes: 0

Muhammed Hafil
Muhammed Hafil

Reputation: 175

use

$("#uploadForm").submit(function () {
      var formData = new FormData(this);
      $.ajax({
          url: '/tab10/uploadImage',
          type: 'POST',
          data: formData,
          async: false,
          cache: false,
          contentType: false,
          processData: false,
          success: function () {
              alert('Form Submitted!');
          },
          error: function(){
              alert("error in ajax form submission");
          }
      });
      return false;
  });

Upvotes: 1

Related Questions