【问题标题】:How to use MultipartContent without file?如何在没有文件的情况下使用 MultipartContent?
【发布时间】:2016-03-10 07:48:33
【问题描述】:
        [HttpPost]
        [Route("Profile")]
        public async Task<IHttpActionResult> SubmitPhotos()
        {
            // Check if the request contains multipart/form-data.   // shivam agarwal
            if (!Request.Content.IsMimeMultipartContent())
            {
                ModelState.AddModelError("MIME not supported", "MIME not supported");

                return BadRequest();
            }



            string root = HttpContext.Current.Server.MapPath("~/Content/ProfileImages/");

            var provider = new MultipartFormDataStreamProvider(root);


            try
            {


                var newResponse = await Request.Content.ReadAsMultipartAsync(provider);
                // pleae check here


                //provider=new FormDataCollection(Request.Content);
                if (provider.FormData.GetValues("UserId").First() == null || provider.FormData.GetValues("UserId").First() == "")
                {
                    return BadRequest("UserId is required");
                }
                else if (provider.FormData.GetValues("DisplayName").First() == null || provider.FormData.GetValues("DisplayName").First() == "")
                {
                    return BadRequest("DisplayName is required");
                }




                foreach (MultipartFileData fileData in provider.FileData)
                {
                    // Image saving process
                    model.ImageKey = keyvalue[0];

                    // call business function
                    if (!response.Exceptions.Any())
                    {
                        //saving to database

                        return Ok(resultResponse);
                    }

                }

                return Ok();
            }
            catch (System.Exception e)
            {
                ModelState.AddModelError("Exception", e.Message);

                return BadRequest();
            }
            finally
            {
                FlushTempFiles();
            }
        }

我正在使用 webapi 将表单集合值提交到数据库。主要输入是 File(Photo),Displayname,UserID 从移动应用程序用户提交三个输入,它将图像保存到文件夹中,其他两个值保存到数据库中。到现在一切都很好。

我的问题是:在我的情况下文件输入是可选的,所以真正的事情是他们可能会也可能不会上传文件输入(Filedata)


所以,我在这一行遇到错误

   var newResponse = await Request.Content.ReadAsMultipartAsync(provider);

MIME 多部分流意外结束。 MIME 多部分消息不完整。

我已经阅读了将 \r\n 添加到流中的答案,但在我的情况下它不起作用。请告诉我您的意见,我该如何处理可选文件输入并仅获取 userid 和 displayname 的值?

【问题讨论】:

    标签: c# file-upload asp.net-web-api asp.net-web-api2 multipartform-data


    【解决方案1】:

    我认为您只需要检查您的移动客户端应用程序。如果您的移动应用是安卓应用,那么您可以参考以下示例代码:

    如果使用 OkHttp:

                OkHttpClient client = new OkHttpClient();
                RequestBody requestBody = new MultipartBuilder()
                        .type(MultipartBuilder.FORM)
                        .addPart(
                                Headers.of("Content-Disposition", "form-data; name=\"title\""),
                                RequestBody.create(null, "Square Logo"))
    //                    .addPart(
    //                            Headers.of("Content-Disposition", "form-data; name=\"file\"; filename=\"myfilename.png\""),
    //                            RequestBody.create(MEDIA_TYPE_PNG, bitmapdata))
                        .build();
                final Request request = new Request.Builder()
                        .url("http://myserver/api/files")
                        .post(requestBody)
                        .build();
    

    如果使用Volley,可以参考My GitHub sample,有需要注意的地方

    // send multipart form data necesssary after file data
    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
    

    我在 Web API 的调试屏幕,你可以看到 FileData.Count 是 0:


    更新:

    IMO,您还应该阅读以下内容:

    Sending HTML Form Data in ASP.NET Web API: File Upload and Multipart MIME

    在那里,你会发现:

    通过查看示例请求,最容易理解多部分 MIME 消息的格式:

    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--
    

    因此,例如,如果您的客户端应用程序没有发送最后一个 -----------------------------41184676334--,您的 Web API 将抛出 Unexpected end of MIME multipart stream. MIME multipart message is not complete.

    【讨论】:

    • 我会检查并通知您。
    • 所以,总之你是说应该在移动端处理吧?
    • 是的,如果你的应用是 Android 的,并且使用了一些库,比如 OkHttp、Retrofit 或 Apache 的 HttpMime,那么它们会为你处理。在我的 Volley 示例中,由于我不使用任何库,所以我必须手动添加 dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
    • 你也可以参考我使用 OkHttp lib 的示例项目,github.com/ngocchung/MultipartOkHttp
    • 我正试图抓住你的移动开发者,他一直在否认我的建议。我现在接受你的回答。这似乎很好的解释。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-30
    • 1970-01-01
    相关资源
    最近更新 更多