jeudi 23 février 2017

read json data and image file as multipart form data in web api 2

I want to post mutipart form data like below to WEB API 2 controller. My data will have JSON and Image file. Please help me how the c# api controller code will be for the below data.

At present I am getting error at"Request.Content.ReadAsMultipartAsync(provider);" Error message: "Unexpected end of MIME multipart stream. MIME multipart message is not complete". I could not further anything.

        var uploadPath = HttpContext.Current.Server.MapPath("~/Userimage/");
        Directory.CreateDirectory(uploadPath);
        var provider = new MultipartFormDataStreamProvider(uploadPath);
        await Request.Content.ReadAsMultipartAsync(provider);

        // Files
        //
        foreach (MultipartFileData file in provider.FileData)
        {
            Debug.WriteLine(file.Headers.ContentDisposition.FileName);
            Debug.WriteLine("File path: " + file.LocalFileName);
        }

        // Form data
        //
        foreach (var key in provider.FormData.AllKeys)
        {
            foreach (var val in provider.FormData.GetValues(key))
            {
                Debug.WriteLine(string.Format("{0}: {1}", key, val));
            }
        }
        return Request.CreateResponse(HttpStatusCode.OK);

---------------------------acebdf13572468
Content-Disposition: form-data; name="modelclass"
Content-Type: application/json

{
"MessageID": 1,
"SenderID": 2,
"userType": "sample string 3",
"msgCategory": "sample string 4",
"msgContent": "sample string 5",
"msgDistributedTo": "sample string 6"
}
---------------------------acebdf13572468
Content-Disposition: form-data; name="fieldNameHere"; filename="bg4.jpg"
Content-Type: image/jpeg

<@INCLUDE C:\Users\Lenovo1\Pictures\bg4.jpg@>
---------------------------acebdf13572468--




Aucun commentaire:

Enregistrer un commentaire