0

I have a function through which I am calling my REST API. I need to pass the image in the request. How do I achieve that?

for ex :

public int Save(Image image)
{
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
    req.Method = "POST";
    HttpWebResponse response = (HttpWebResponse)req.GetResponse();
}

here, how do I pass my 'image' to my request 'req'?

Daniel B
  • 8,770
  • 5
  • 43
  • 76
Bucky
  • 1
  • 1
  • 1

2 Answers2

1

Try to use something like:

req.ContentType = "multipart/form-data";

using (var ms = new MemoryStream())
{
    image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); //if it is jpeg
    string encoded = Convert.ToBase64String(ms.ToArray());
    byte[] reqData = Encoding.UTF8.GetBytes(encoded);
    using (var stream = req.GetRequestStream())
    {
        stream.Write(reqData, 0, reqData.Length);
    }
}
Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116
0

You could do something like this on the client side:

HttpClient client = new HttpClient();
var imageStream = File.OpenRead(@"C:\p1.jpg");
var content = new StreamContent(imageStream);
content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
var response = await client.PostAsync("URL", content);

You can get HttpClient from the NugetPackage Microsoft.Net.Http

On the REST API side (receiving end), you can then take it from the Request.Content object, something like this:

public void Post()
{
            using (var fileStream = File.Create("C:\\NewFile.jpg"))
            {
                using (MemoryStream tempStream = new MemoryStream())
                {
                    var task = this.Request.Content.CopyToAsync(tempStream);
                    task.Wait();

                    tempStream.Seek(0, SeekOrigin.Begin);
                    tempStream.CopyTo(fileStream);
                    tempStream.Close();
                }

            }
 }
Abey
  • 101
  • 2
  • 10