How to send WinForm images to a C # WebAPI service on both sides

6

I have two applications, a WinForm running location and a WebApi hosted remote.

I already send data to the server from WinForm, the code looks like this:

JavaScriptSerializer json_serializer = new JavaScriptSerializer();

string DATA = json_serializer.Serialize(MEUOBJETO);


HttpWebRequest request;

request = (HttpWebRequest)WebRequest.Create(URL);

request.Method = "POST";
request.Proxy = null;
request.ContentType = "application/json";

byte[] dataStream = Encoding.UTF8.GetBytes(DATA);
Stream newStream = request.GetRequestStream();
newStream.Write(dataStream, 0, dataStream.Length);
newStream.Close();

request.GetResponse();

I would like to know how I can put an image in this MEUOBJETO to serialize everything together and send.

Would you do it? How would the server side look?

My server receives the data as follows:

[Route("MINHA ROTA")]
public HttpResponseMessage POST( [FromBody]MEUOBJETO obj)
{

  if (ModelState.IsValid)
  {
   ...
  }
}
    
asked by anonymous 20.05.2015 / 16:43

1 answer

5

You can use a property of type String in MEUOBJETO and load the serialized image as a Base64 string:

string imagemBase64 = Convert.ToBase64String(umaImagem); // umaImagem é um byte[]
MEUOBJETO.ImagemBase64 = imagemBase64;
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
string DATA = json_serializer.Serialize(MEUOBJETO);

Then, on the Web.API side, just convert back to byte[] :

[Route("MINHA ROTA")]
public HttpResponseMessage POST([FromBody]MEUOBJETO obj)
{
    byte[] imagem = Convert.FromBase64String(obj.ImagemBase64);
    if (ModelState.IsValid)
    {

    }
}
    
20.05.2015 / 17:03