How to send Winform images to a Webapi service c# on both sides

Asked

Viewed 660 times

6

I have two apps, a local running Winform and a remote hosted Webapi.

Already send data to the served from Winform, the code is 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 wonder how I can put an image in this MEUOBJETO to serialize everything together and send.

Could you do that? What the Server side would look like?

My server receives the data as follows:

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

  if (ModelState.IsValid)
  {
   ...
  }
}

1 answer

5


You can use a property of the type String in the MEUOBJETO and upload the serialized image as 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, from the Web side.API is just convert back to byte[]:

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

    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.