将图像发送到WebApi服务

时间:2015-10-27 12:19:01

标签: c# asp.net rest windows-phone-8.1 asp.net-web-api

我在Windows Phone上制作了一个项目,用户可以在其中拍照,将其保存在手机上,然后再上传到我的服务器上。所以有两个项目,WP8.1和ASP.NET WEB API。

目前我不知道如何将照片上传到我的服务器(来自手机),我甚至不知道如何在API中捕获它。最好的方法是什么?

这是我在屏幕(手机)上显示的方法,用户拍摄的照片。

private async void LoadCapturedphoto(string filename)
    {
        //load saved image
        StorageFolder pictureLibrary = KnownFolders.SavedPictures;
        StorageFile savedPicture = await pictureLibrary.GetFileAsync(filename);
        ImageProperties imgProp = await savedPicture.Properties.GetImagePropertiesAsync();
        var savedPictureStream = await savedPicture.OpenAsync(FileAccessMode.Read);

        //set image properties and show the taken photo
        bitmap = new WriteableBitmap((int)imgProp.Width, (int)imgProp.Height);
        await bitmap.SetSourceAsync(savedPictureStream);
        takenImage.Source = bitmap;
        takenImage.Visibility = Visibility.Visible;

    }

我认为我应该将WriteableBitmap转换为Byte [],通过API将这些Byte []发送到服务器,并在服务器上将Byte []转换为JPG / PNG /等。

private byte[] ConvertBitmapToByteArray(WriteableBitmap bitmap)
    {
        WriteableBitmap bmp = bitmap;

        using (Stream stream = bmp.PixelBuffer.AsStream())
        {
            MemoryStream memoryStream = new MemoryStream();
            stream.CopyTo(memoryStream);
            return memoryStream.ToArray();
        }
    }

有什么想法吗?你觉得这样做是不错的主意? WriteableBitmap - > Byte []和服务器上的下一个Byte [] - > JPG / PNG等甚至可能吗?

如果可以做得更容易,请写一些样本。

它是我调用api方法的方法

public string apiCommand(string api, string json)
    {
        using (var httpClient = new HttpClient())
        {
            HttpContent content = new StringContent(json, Encoding.UTF8);
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            HttpResponseMessage response = httpClient.PostAsync(Variables.apiURL + api, content).Result;
            response.EnsureSuccessStatusCode();

            Task<string> responseBody = response.Content.ReadAsStringAsync();
            //var msg = new MessageDialog(responseBody.Result.ToString());

            if (response.StatusCode.ToString() != "OK")
            {
                return "ERROR: " + response.StatusCode.ToString();
            }
            else
            {
                return "SUCCES: " + responseBody.Result.ToString();
            }
        }
    }

2 个答案:

答案 0 :(得分:2)

您需要对服务器使用multipart / form-data请求。您可以使用有效负载字段将json发送到Web api(另一种方法是分别发送每个字段,但是您需要反思才能这样做。)

这可能会对你有帮助:

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

答案 1 :(得分:1)

我以此方式处理项目中的图像和文字文件,希望对您有所帮助。

1)服务器端,我有一个通用的api方法来处理Json请求。

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

客户端, 1)通过.net代码调用,我使用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)通过JavaScript调用它,通常我会在网站控制器中创建一个方法,并将json请求转发到上述定义的方法。如果您的JavaScript代码和api代码共享相同的json对象,则非常简单。

2.1)网站控制器代码,

[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调用示例代码:

    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
    });
相关问题