I\'m making a project on Windows Phone where user can take a photo, save it on phone and next upload on my server. So there are two projects, WP8.1 and ASP.NET WEB API.
I handle image and word files in my project by this way, hope it helps.
1) Server side, I have a generic api method to process Json requests.
[HttpPost]
public HttpResponseMessage ProcessRequest([FromBody] string sJsonRequest)
{
ResponseMsg rspMsg = null;
RequestMsg oRequestMsg = null;
string sDeteializeMsg = "";
try
{
string sUnescapeJsonData = System.Uri.UnescapeDataString(sJsonRequest);
sJsonRequest = sUnescapeJsonData;
oRequestMsg = (RequestMsg)JsonHelper.Deserialize(typeof(RequestMsg), sJsonRequest);
}
catch (Exception ex)
{
...
}
if (oRequestMsg == null)
{
return AppHelper.GetUTF8PlainTextHttpResponse(@"Invalid request message.");
}
rspMsg = new ResponseMsg(oRequestMsg);
string sJsonRet = "";
try
{
if(oRequestMsg.RequestType==SavingFile)
{
byte[] bytes = System.Convert.FromBase64String(oRequestMsg.Base64Data);
System.IO.File.WriteAllBytes(sFileName, bytes);
....
}
//update rspMsg ....
}
catch (Exception ex)
{
...
}
finally
{
sJsonRet = JsonHelper.Serialize(rspMsg);
}
return AppHelper.GetUTF8PlainTextHttpResponse(sJsonRet);
}
Client side, 1) call through .net code, I use system.Net.webclient,
system.Net.webclient cli=new system.Net.webclient();
cli.Credentials = Credentials;
cli.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
//http://blogs.msdn.com/b/jmstall/archive/2012/04/16/how-webapi-does-parameter-binding.aspx
sJsonRequest = "=" + EscapeDataStringBig(sJsonRequest);
response = cli.UploadString(sRemoteUrl, "POST", sJsonRequest);
ResponseMsg rsp = (ResponseMsg)JsonHelper.Deserialize(typeof(ResponseMsg), response);
return rsp;
2) call it through JavaScript, usually I will create a method in website controller and forward the json request to the method defined as above. if your javascript code and api code share same json objects, it is quite easy.
2.1) web site controller code,
[HttpPost]
public ActionResult AjaxRequest(int nPostType = -1, string sJsonObject = "")
{
try
{
WebModelAjaxRequestTypes nReqType = (WebModelAjaxRequestTypes)nPostType;
bool bIsBase64Data = IsBase64Request(nReqType);
string sJsonRet = "";
if (!bIsBase64Data)
{
....
}
else
{
//base64 content requests
string sBase64Data = sJsonObject;
//put the string into a json request and send it to api call. and get the return => sJsonRet
}
return Content(sJsonRet); }
catch (Exception ex)
{
....
}
}
2.2) JavaScript ajax call sample code:
var type = "POST";
var sContentType = "";
var sData = ""
if (bIsBase64) {
//sJsonParas is base64 string. don't use encodeURI to encode it.!!!
sContentType = 'application/json; charset=utf-8';
sData = '{ "nPostType" :' + nPostType.toString() + ',"sJsonObject" : "' + sJsonParas + '" }';
}
else {
sContentType = "application/x-www-form-urlencoded; charset=UTF-8";
sData = "nPostType=" + nPostType.toString() + "&sJsonObject=" + encodeURIComponent(sJsonParas);
}
jQuery.ajax({
url: sUrl,
type: type,
data: sData,
contentType: sContentType,
success: function (result) {
....
},
error: function (jqXHR, textStatus, errorThrown) {
....
},
complete: function (jqXHR, textStatus) {
....
} //end complete
});
You need to use multipart/form-data request to the server. You can send the json to the web api using payload field (another alternative is send every field separately, but you need reflection to do that.)
This maybe can help you:
public string UploadUserPictureApiCommand(string api, string json, byte[] picture)
{
using (var httpClient = new HttpClient())
{
MultipartFormDataContent form = new MultipartFormDataContent();
form.Add(new StringContent(json), "payload");
form.Add(new ByteArrayContent(picture, 0, picture.Count()), "user_picture", "user_picture.jpg");
HttpResponseMessage response = await httpClient.PostAsync(api, form);
response.EnsureSuccessStatusCode();
Task<string> responseBody = response.Content.ReadAsStringAsync();
if (response.StatusCode.ToString() != "OK")
{
return "ERROR: " + response.StatusCode.ToString();
}
else
{
return "SUCCES: " + responseBody.Result.ToString();
}
}
}