Sending HTTP POST Multipart/form-data field using RestSharp Sending HTTP POST Multipart/form-data field using RestSharp json json

Sending HTTP POST Multipart/form-data field using RestSharp


So I am doing this by working around a problem with using the AddBody method which automatically kills the multi part form images and will not send them. You must use add parameter instead.

To solve this problem you may have to do a little work on both sides of the communication.

To send the message from the client you do the following:

new RestRequest("<Your URI>");request.AddParameter("request", tokenRequest.ToJson());request.AddFile("front", frontImage.CopyTo, "front");request.AddFile("back", backImage.CopyTo, "back");request.AddHeader("Content-Type", "multipart/form-data");

On my web service side, I accept the json as the argument to the method and manually obtain a reference to the file streams:

public JsonResult MyService(StoreImageRequest request){    var frontImage = HttpContext.Request.Files["front"].InputStream;    var backImage = HttpContext.Request.Files["front"].InputStream;}


Multi-part request with JSON body + File parts

If your server can process a multi-part with JSON body and Files parts, then

Client code:

        var req = new RestRequest(UPLOAD_DOC_URLSEGMENT, Method.POST);        req.RequestFormat = DataFormat.Json;        req.AddBody(doc);        req.AddFileBytes("TestImage", Properties.Resources.TestImage, "TestImage.jpg");        req.AddHeader("apikey", "MY-API-KEY");        var resp = restClient.Execute<ApiResult>(req);

Server code:

At the server side such multi-part request should be processed as:

    [HttpPost]    public JsonResult UploadDoc()    {        // This is multipart request. So we should get JSON from http form part:        MyDocModel doc = JsonConvert.DeserializeObject<MyDocModel>(Request.Form[0]);                foreach (string fileName in request.Files)        {            HttpPostedFileBase file = request.Files[fileName];        }