1、通过读取路径将文件转为byte[]
//将一个file文件转化为byte[] public static byte[] GetBytesFromUrl1(string url) { byte[] b; FileWebRequest myReq = (FileWebRequest)WebRequest.Create(url); WebResponse myResp = myReq.GetResponse(); Stream stream = myResp.GetResponseStream(); //int i; using (BinaryReader br = new BinaryReader(stream)) { b = br.ReadBytes(1000000); br.Close(); } myResp.Close(); return b; }
//通过Url地址将文件转成byte[] public static byte[] GetBytesFromUrl(string url) { byte[] b; HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url); WebResponse myResp = myReq.GetResponse(); Stream stream = myResp.GetResponseStream(); //int i; using (BinaryReader br = new BinaryReader(stream)) { b = br.ReadBytes(500000); br.Close(); } myResp.Close(); return b; }
2、通过接口传递图片文件方法
请求代码:
string filePath = @"F: eTestimage12.jpg"; byte[] bt = GetBytesFromUrl1(filePath); string str = Convert.ToBase64String(bt);
StringBuilder sb = new StringBuilder();
sb.Append("filename=" + HttpUtility.UrlEncode("as", Encoding.UTF8));
sb.Append("&fileimg=" + HttpUtility.UrlEncode(str, Encoding.UTF8));
string res = HttpHelper.httpPost("接口地址", sb.ToString());
接口地址接收代码:
string str = Request["fileimg"] ?? "";
string filename = Request["filename"]??"";
byte[] byt = Convert.FromBase64String(str);
FileStream fs = new FileStream(@"D:xxwebaabimages" + filename + ".jpg", FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
//开始写入
bw.Write(byt, 0, byt.Length);
//关闭流
bw.Close();
fs.Close();
然后可以出来byt图片文件了