0

How do I send FormData to a controller? I am trying to upload an image:

$(".Replybtn").on("click", function() {

  var fileData = new FormData();
  var files = $(".Rfile[data-id=" + RId + "]").get(0).files;

  if (files.length > 0) {
    fileData.append("HelpSectionImages", files[0]);
  }

  $.post('/QJN/Reply/', {
    __RequestVerificationToken: gettoken(),
    TGID: RId,
    SID: UId,
    Com: cmnt
  }, function(data) {
    if (data == "Tagged") {
      // 
    }
  });

});

HTML

<input type="file" class="Rfile" [email protected] accept = "image/*,video/*">

Controller

   [HttpPost, ValidateAntiForgeryToken, ValidateInput(enableValidation: true)]
    public ActionResult Reply(string TGID, string SID, string Com)
    {
     var file = Request.Files["HelpSectionImages"]; 
      if(file!=null){

       }
     }
3
  • Could you please post your controller action and any relevant HTML? Here is the jQuery docs on .post() - does your request follow these guidelines? Commented May 12, 2017 at 20:29
  • Hi,I have updated question Commented May 12, 2017 at 20:35
  • Is your post request hitting your controller action? Please let us know if @er-han's answer resolves your issue (and if it does, please accept it.) Commented May 12, 2017 at 22:53

1 Answer 1

1

It seems you are not posting fileData object. So you don't get any files from Request.

Try this:

$(".Replybtn").on("click", function () {
var fileData = new FormData();

var files = $(".Rfile[data-id=" + RId + "]").get(0).files;  

if (files.length > 0) {
    fileData.append("HelpSectionImages", files[0]); 
}

fileData.append("__RequestVerificationToken", gettoken());
fileData.append("TGID", RId);
fileData.append("SID", UId);
fileData.append("Com", cmnt);

$.ajax({
  url: '/QJN/Reply/',
  data: fileData,
  processData: false,
  contentType: false,// only jQuery 1.6+
  type: 'POST',
  success: function(data){
    if (data == "Tagged") {

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

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.