Method of C Remote Sending and Receiving Data Stream to Generate Picture
- 2021-07-22 11:08:26
- OfStack
This paper describes the method of C # remote sending and receiving data streams to generate pictures. Share it for your reference. The details are as follows:
Transform the picture into data stream and send it to the remote service, receive the data stream through the server background program, and then save it into a picture and store it in the required place.
This way is similar to upload picture function 1, I hope to give you another way to upload picture function.
Send data stream method
/// <summary>
/// PostBinaryData
/// </summary>
/// <param name="url"> To send url Web site </param>
/// <param name="bytes"> Data stream to send </param>
/// <returns></returns>
public string PostBinaryData(string url, byte[] bytes)
{
// The following is a test example
//string url = "http://www.test.com/test.ashx";
//string img = HttpContext.Current.Server.MapPath("../images/test.jpg");
//byte[] bytes = File.ReadAllBytes(img);
HttpWebRequest wRequest = (HttpWebRequest)WebRequest.Create(url);
wRequest.ContentType = "multipart/form-data";
wRequest.ContentLength = bytes.Length;
wRequest.Method = "POST";
Stream stream = wRequest.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream.Close();
HttpWebResponse wResponse = (HttpWebResponse)wRequest.GetResponse();
StreamReader sReader = new StreamReader(wResponse.GetResponseStream(), System.Text.Encoding.UTF8);
string str = sReader.ReadToEnd();
sReader.Close();
wResponse.Close();
return str;
}
Method for receiving data stream
public void GetBinaryData()
{
string imgFile = DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpg";
string filePath = HttpContext.Current.Server.MapPath(imgFile);
// Method 1
int lang = HttpContext.Current.Request.TotalBytes;
byte[] bytes = HttpContext.Current.Request.BinaryRead(lang);
string content = System.Text.Encoding.UTF8.GetString(bytes);
FileStream fStream = new FileStream(filePath, FileMode.Create, FileAccess.Write);
BinaryWriter bw = new BinaryWriter(fStream);
bw.Write(bytes);
bw.Close();
fStream.Close();
// Method 2
Bitmap img = new Bitmap(HttpContext.Current.Request.InputStream);
img.Save(filePath);
HttpContext.Current.Response.Write("ok");
}
I hope this article is helpful to everyone's C # programming.