【问题标题】:How to pass multipart/form-data to c# method via Ajax如何通过 Ajax 将 multipart/form-data 传递给 c# 方法
【发布时间】:2013-12-04 13:32:16
【问题描述】:

我正在使用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
}

【问题讨论】:

    标签: c# jquery ajax


    【解决方案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/

    【讨论】:

    • 如果我放置一个参数接受类型“HttpPostedFileBase”,该方法甚至不会被命中
    • 你的表单上是否有这样的元素:
    • 我不需要输入文件类型,正如我在上面的帖子中已经说过的那样,我正在使用为我提供 base64 数据的插件,并且我想将它传递给 c# 方法。反正有没有直接通过ajax传递base64数据?
    • 您是否尝试在参数中输入字符串? stackoverflow.com/questions/6754551/…
    猜你喜欢
    • 2019-02-26
    • 2019-04-05
    • 2022-07-29
    • 1970-01-01
    • 1970-01-01
    • 2019-08-27
    • 2011-04-22
    • 2011-08-21
    相关资源
    最近更新 更多