如何通过Ajax将multipart / form-data传递给c#方法

时间:2013-12-04 13:32:17

标签: c# jquery ajax

我正在使用html2canvs.js来截取此处描述的页面的屏幕截图: How to take screen shot of current webpage using javascript/jquery

上面的过程运行正常,但现在我想通过ajax将Base64数据传递给c#方法。我的代码如下:

$('#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 () {

            }
        });
    }
});

这是我的c#方法

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

1 个答案:

答案 0 :(得分:1)

尝试一下:

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

}

表格

对象FormData将保存要发送的文件元素。

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

参考文献:

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/