muyier

使用JavaScript的XMLHttpRequest+fromdata 传递blob到后端

需要上传网页录音文件到服务器,写的艰辛,终于好了,失败代码的留作纪念

JavaScript:

//  方法失败

//    $.ajax({
        //    url: "/Home/SRTest",
        //    type: "POST",
        //    data: form,
        //    contentType: false,
        //    processData: false,
        //    success: function (response) {
        //        alert(response);
        //    }
        //})

// 最终成功方法

var form = new FormData();

form.enctype = "multipart/form-data";

form.append("blob", blob, "myvoice");

var xhr = new XMLHttpRequest();

xhr.open("POST", "/Home/SRTest");

xhr.send(form);

 

C#

  [HttpPost]
        public JsonResult SRTest(FormCollection formCollection)
        {
            //other way to get formdata
   // 方法1 失败
            //var httpRequest = System.Web.HttpContext.Current.Request;
            //string blob = httpRequest.Form["blob"];
    // 方法1.1 失败
            //string blob1 = httpRequest.Form["myvoice"];
    // 方法2失败
            //string blob2 = formCollection["blob"];
    // 方法2.1失败
            //string blob21 = formCollection["myvoice"];
    // 方法3失败
            //HttpPostedFileBase blob3 = Request.Files["blob"];
    // 方法3.1失败
            //HttpPostedFileBase blob31 = Request.Files["myvoice"];
    // 方法4失败
            //string blob4 = Request.Form["blob"];
       // 方法4.1失败
            //string blob41 = Request.Form["myvoice"];
 
   //最终成功方法
            HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
            HttpPostedFile file = files[0];
 
功能完成了很开心

posted on 2019-08-02 16:45  muyier  阅读(1330)  评论(0编辑  收藏  举报

导航