Ammar Khan
Ammar Khan

Reputation: 356

How to pass multipart/form-data to c# method via Ajax

I am using html2canvs.js for taking screen shots of the page which is described here: How to take screen shot of current webpage using javascript/jquery

The above process works fine, but now I want to pass the Base64 data to a c# method via ajax. My code looks like:

$('#gbox_Basic').html2canvas({
    onrendered: function (canvas) {
        var imgString = canvas.toDataURL("image/png");
        $.ajax({
            type: "POST",
            url: "/Home/SentEmail2",
            data: //how to pass base64 data 'imgString' ,
            contentType: "multipart/form-data",
            success: function () {

            }
        });
    }
});

And here is my c# method

public void SentEmail2(what type of param it would accept?) {
    //process incoming params
}

Upvotes: 0

Views: 2536

Answers (1)

ismatim
ismatim

Reputation: 186

Give a try to this:

Controller.cs

 [HttpPost]
 public ActionResult Index(HttpPostedFileBase file) {

 if (file.ContentLength > 0) {
   var fileName = Path.GetFileName(file.FileName);
   var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
   file.SaveAs(path);
}

return RedirectToAction("Index");

}

Form

The object FormData will hold the file element to be send.

var formData = new FormData($('form')[0]);
$.ajax({
    url: '/Home/SentEmail2',  //Server script to process data
    type: 'POST',
    xhr: function() {  // Custom XMLHttpRequest
        var myXhr = $.ajaxSettings.xhr();
          if(myXhr.upload){ // Check if upload property exists
            myXhr.upload.addEventListener('progress',progressHandlingFunction, false);         // For handling the progress of the upload
        }
        return myXhr;
    },
    //Ajax events
    beforeSend: beforeSendHandler,
    success: completeHandler,
    error: errorHandler,
    // Form data
    data: formData,
    //Options to tell jQuery not to process data or worry about content-type.
    cache: false,
    contentType: false,
    processData: false
});

References:

http://www.dustinhorne.com/post/2011/11/16/AJAX-File-Uploads-with-jQuery-and-MVC-3

http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx/

Upvotes: 1

Related Questions