当前位置: 移动技术网 > IT编程>开发语言>c# > C#远程发送和接收数据流生成图片的方法

C#远程发送和接收数据流生成图片的方法

2019年07月18日  | 移动技术网IT编程  | 我要评论
本文实例讲述了c#远程发送和接收数据流生成图片的方法。分享给大家供大家参考。具体如下: 将图片转成数据流方式发送到远程服务,在通过服务器后台程序来接收数据流,再保存成图片

本文实例讲述了c#远程发送和接收数据流生成图片的方法。分享给大家供大家参考。具体如下:

将图片转成数据流方式发送到远程服务,在通过服务器后台程序来接收数据流,再保存成图片存放在需要的地方。

这种方式就类似上传图片功能一样,希望能给一些大家另一种上传图片功能的方法。

发送数据流方法

/// <summary>
/// postbinarydata
/// </summary>
/// <param name="url">要发送的 url 网址</param>
/// <param name="bytes">要发送的数据流</param>
/// <returns></returns>
public string postbinarydata(string url, byte[] bytes)
{
  //下面是测试例子
  //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;
}

接收数据流方法

public void getbinarydata()
{
  string imgfile = datetime.now.tostring("yyyymmddhhmmss") + ".jpg";
  string filepath = httpcontext.current.server.mappath(imgfile);
  //方法一
  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();    
  //方法二
  bitmap img = new bitmap(httpcontext.current.request.inputstream);
  img.save(filepath);
  httpcontext.current.response.write("ok");
}

希望本文所述对大家的c#程序设计有所帮助。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网