Search code examples
c#asp.nethttpwebrequesthttphandlerbinary-data

How to post a binary image from desktop app to ashx handler and receive it?


I am developing a WinForms application and want to send a binary image data to web application. How does it work?

I coded this:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";

request.AllowWriteStreamBuffering = true;
request.KeepAlive = true;                
request.Credentials = System.Net.CredentialCache.DefaultCredentials;

var fc = GetFileContent(varsayilanResimGuid);
byte[] postBytes = fc.Dosya;
request.ContentLength = postBytes.LongLength;
Stream requestStream = request.GetRequestStream();               
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();                

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string content = new StreamReader(response.GetResponseStream()).ReadToEnd(); 

and how to receive this binary image content by me in .ashx ?


Solution

  • I question and I answer.
    how to receive a binary image:

    Stream gelenResim = context.Request.InputStream;
    
    if (gelenResim.Length == 0) 
    {
        e.Resim = "/Content/EmlakDetayImaj/Noimages.jpg";
    }
    
    string guidim = Guid.NewGuid().ToString().Substring(0, 4);
    var KaydetResimDosya = "/Content/EmlakDetayImaj/" + guidim + ".jpg";
    
    using (FileStream fileStream = System.IO.File.Create(context.Server.MapPath("~/Content/EmlakDetayImaj/" + guidim + ".jpg"), (int)gelenResim.Length))
    {
        byte[] bytesInStream = new byte[gelenResim.Length];
        gelenResim.Read(bytesInStream, 0, (int)bytesInStream.Length);
        fileStream.Write(bytesInStream, 0, bytesInStream.Length);
    }