最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Sending formdata for file upload using ajax - Stack Overflow

programmeradmin4浏览0评论

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.

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.

Share Improve this question edited Oct 6, 2017 at 10:10 Srijan Sharma asked Oct 6, 2017 at 10:04 Srijan SharmaSrijan Sharma 6931 gold badge9 silver badges21 bronze badges 5
  • try to use full url. – Himanshu Upadhyay Commented Oct 6, 2017 at 10:06
  • FYI: async: false, synchronous requests in the main thread are deprecated - avoid it – Jaromanda X 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 – Jaromanda X 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 – Srijan Sharma Commented Oct 6, 2017 at 10:07
  • oh ok @SrijanSharma – Himanshu Upadhyay Commented Oct 6, 2017 at 10:13
Add a ment  | 

3 Answers 3

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

  });

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

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) {
        }
});
发布评论

评论列表(0)

  1. 暂无评论