Just code
Just code

Reputation: 13801

How to use MultipartContent without file?

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

I am using webapi to submit the form-collection values to the database. The main inputs are File(Photo),Displayname,UserID From the mobile application user submits the three inputs it saves the image into the folder and other two values into the database. till now everything is fine.

My problem is: the file input is optional in my case, so the real thing is they may or may not upload the file input (Filedata)


So, I am getting error in this line

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

Unexpected end of MIME multipart stream. MIME multipart message is not complete.

I have read the answers to add the \r\n to the stream but it is not working in my case. Please tell me your opinion how can I handle the optional file input and just get the values of userid and displayname?

Upvotes: 1

Views: 2444

Answers (1)

BNK
BNK

Reputation: 24114

I think you only need to check your mobile client app. If your mobile app is an Android app, then you can refer to the following sample codes:

If using 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();

If using Volley, you can refer to My GitHub sample, there you should pay attention to

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

My debug screen at Web API, you can see FileData.Count is 0:

enter image description here


UPDATE:

IMO, you should also read the following:

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

There, you will find:

The format of a multipart MIME message is easiest to understand by looking at an example request:

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

So, if your client app did not send the last -----------------------------41184676334--, for example, your Web API will throw Unexpected end of MIME multipart stream. MIME multipart message is not complete.

Upvotes: 1

Related Questions