【问题标题】:ASP Net Web Form Web API - FormData is empty if file is attachedASP Net Web Form Web API - 如果附加文件,FormData 为空
【发布时间】:2014-05-30 10:32:05
【问题描述】:

我正在使用 Asp net web form 4.5.1 和 Asp net web Api,我试图将一些数据和文件发送到 Web Api 方法, 我的代码基于[http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-2][1] 示例 但我想通过 AJAX (jquery) 发送数据

var formData = new FormData();
                var opmlFile = $('#packFile')[0];
                formData.append("opmlFile", opmlFile.files[0]);
                formData.append("packageData",  JSON.stringify(ko.mapping.toJS(this.selectedItem)));

                $.ajax({
                    type: "POST",
                    url: "/api/MyController/MyMethod",                   
                    dataType: "json",
                    data: formData,
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function (response) {

                    },
                    failure: function (response) {

                    }
                });

这似乎是可行的情况,但如果我在请求中发送文件,我的对象数据不可用(provider.FormData.AllKeys)。如何使它起作用?当然我可以发送 2 个请求,但这似乎对我不利。

public async Task<HttpResponseMessage> MyMethod()
    {
        // Check if the request contains multipart/form-data.
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        string root = HttpContext.Current.Server.MapPath("~/App_Data");
        var provider = new MultipartFormDataStreamProvider(root);

        // Read the form data and return an async task.
        var task = Request.Content.ReadAsMultipartAsync(provider).
            ContinueWith<HttpResponseMessage>(t =>
            {
                if (t.IsFaulted || t.IsCanceled)
                {
                    Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
                }

                // This illustrates how to get the file names.
                foreach (MultipartFileData file in provider.FileData)
                {
                    Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                    Trace.WriteLine("Server file path: " + file.LocalFileName);
                }

                foreach (var key in provider.FormData.AllKeys)
                {
                    foreach (var val in provider.FormData.GetValues(key))
                    {
                        Trace.WriteLine(string.Format("{0}: {1}", key, val));
                    }
                }

                return Request.CreateResponse(HttpStatusCode.OK);
            });

        return await task;

    }

【问题讨论】:

    标签: jquery asp.net ajax asp.net-web-api multipartform-data


    【解决方案1】:

    这里您的多部分请求包含 JSON + 文件数据,而 MultipartFormDataStreamProvider 需要表单数据 + 文件...一个典型的多部分表单数据请求的示例...注意名为 Content-Disposition: form-data 的标头。 .

    POST http://localhost:50460/api/values/1 HTTP/1.1
    User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    Accept-Language: en-us,en;q=0.5
    Accept-Encoding: gzip, deflate
    Content-Type: multipart/form-data; boundary=---------------------------41184676334
    Content-Length: 29278
    
    -----------------------------41184676334
    Content-Disposition: form-data; name="caption"
    
    Summer vacation
    -----------------------------41184676334
    Content-Disposition: form-data; name="image1"; filename="GrandCanyon.jpg"
    Content-Type: image/jpeg
    
    (Binary data not shown)
    -----------------------------41184676334--
    

    对于您的场景,您可以创建一个从抽象 MultipartStreamProvider 派生的自定义多部分流提供程序,或者您可以执行以下操作:

    Customer customer = null;
    foreach(HttpContent content in provider.Contents)
    {
        if(content.Headers.ContentType.MediaType == "application/json")
        {
            customer = await content.ReadAsAsync<Customer>();
            break;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-05-18
      • 1970-01-01
      • 2013-09-15
      • 2017-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多