While I was working with the REST API to upload an image using RestSharp, I encountered a problem uploading it. I Googled the problem but did not find a specific answer for it. Although I found the solution and thought to share it since it can save a lot of time for other developers. I am assuming here that the reader is familiar with the REST API and RestSharp.
- [OperationContract]
- [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
- public void NotesAttachment(Stream input)
- {
- HttpApplicationState Application = HttpContext.Current.Application;
- HttpRequest Request = HttpContext.Current.Request;
- string sRequest = String.Empty;
- using (StreamReader stmRequest = new StreamReader(input, System.Text.Encoding.UTF8))
- {
- sRequest = stmRequest.ReadToEnd();
- }
- JavaScriptSerializer json = new JavaScriptSerializer();
- json.MaxJsonLength = int.MaxValue;
- Dictionary<string, object> dict = json.Deserialize<Dictionary<string, object>>(sRequest);
- string ext = dict["FILE_EXT"] as string;
- string mime = dict["FILE_MIME_TYPE"] as string;
- string image = dict["IMAGE_DATA"] as string; byte[] attachment = Convert.FromBase64String(image);
- }
What this method (the WS method) is expecting is a Stream object containing a file extension, file mime type and file data as an encoded string that is being converted to a byte array.
JavaScriptSerializer used in the example above is System.Web.Script.Serialization from systems.web.extension.dll.
This is how it is called from the client, I am using WPF as the client, but it can be called from a console or web app.
- private void CallRestNotesAttachment(string ext, string mime)
- {
- var restClient = new RestClient("http://localhost:1608/Rest.svc/NotesAttachment");
- restClient.AddHandler("application/octet-stream", new RestSharp.Deserializers.JsonDeserializer());
- var request = new RestRequest(Method.POST);
- request.AddHeader("Content-Type", "application/octet-stream");
- Dictionary<string, object> dict = new Dictionary<string, object>();
- dict.Add("FILE_EXT", ext);
- dict.Add("FILE_MIME_TYPE", mime);
- byte[] imageBytes;
- using (FileStream fs = File.Open(@"C:\Users\anand.thakur\Desktop\1.wmv", FileMode.Open))
- {
- imageBytes = new BinaryReader(fs).ReadBytes((int)fs.Length);
- }
- string image = Convert.ToBase64String(imageBytes);
- dict.Add("IMAGE_DATA", image);
- byte[] data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(dict));
- request.AddParameter("application/octet-stream", data, ParameterType.RequestBody);
- var response = restClient.Execute(request);
- JavaScriptSerializer json = new JavaScriptSerializer();
- Dictionary<string, object> dict1 = json.Deserialize<Dictionary<string, object>>(response.Content);
- MessageBox.Show("done");
- }
The RestSharp package is available through NuGet. JsonConvert can be found in Newtonsoft.Json, that is also available at NuGet.