1

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.

5
  • try to use full url. Commented Oct 6, 2017 at 10:06
  • FYI: async: false, synchronous requests in the main thread are deprecated - avoid it Commented Oct 6, 2017 at 10:06
  • parameter called "files" is not being send in the later case without seeing the form, it's a true mystery Commented Oct 6, 2017 at 10:07
  • but the request is being sent to the uploadimage function,so how will specifying the full url would be of any use. @HimanshuUpadhyay Commented Oct 6, 2017 at 10:07
  • oh ok @SrijanSharma Commented Oct 6, 2017 at 10:13

3 Answers 3

3

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");
          }
      });

  });
Sign up to request clarification or add additional context in comments.

2 Comments

this also doesn't seem to be working. in the working case this is the information that i get to use for moving the file:{ file: { name: 'images.png', data: <Buffer >, encoding: '7bit', mimetype: 'image/png',mv: [Function: mv] } } which comes along in the req variable itself. however in this case we are getting only basic info like name of the image.
sorry i edited my answer it should be formData.append('file',$('#uploadFile')[0].files[0]); to get the one file.But in some cases when you want to upload multiple files you have to make a loop
1

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;
  });

2 Comments

thanks man...was struggling with it for a long time....can you in brief try to explain the logic as to why was the one that i wrote not working?
new FormData(this); // you were not specifying which formData
0

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) {
        }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.