代码
/// <summary> /// 上传图片到第三方服务器 /// </summary> /// <param name="filePath"></param> /// <param name="picNo"></param> /// <returns></returns> public string UploadFilesToBlueBox(string filePath, string picNo) { string strReturn = ""; string fileName = Path.GetFileName(filePath); string strPostUrl = "http://pic.xxx.com/HttpPost_Upload.aspx?PICID=" + picNo + "&FILENAME=" + fileName; HttpWebRequest reqPost = (HttpWebRequest)WebRequest.Create(strPostUrl); reqPost.Method = "POST"; reqPost.KeepAlive = false; reqPost.ContentType = "application/x-www-form-urlencoded"; byte[] fileStream = AuthGetFileData(filePath);//把文件转为bute[],看之前的博客 string strStream = Convert.ToBase64String(fileStream); byte[] strFiledata = Encoding.UTF8.GetBytes(strStream); reqPost.ContentLength = strFiledata.Length; //post数据 using (Stream newStream = reqPost.GetRequestStream()) { newStream.Write(strFiledata, 0, strFiledata.Length); //获取返回 HttpWebResponse myResponse = (HttpWebResponse)reqPost.GetResponse(); using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8)) { //返回结果 strReturn = reader.ReadToEnd(); } } return strReturn; }
文件转byte[]
/// <summary> /// 将文件转换成byte[] 数组 /// </summary> /// <param name="fileUrl">文件路径文件名称</param> /// <returns>byte[]</returns> public byte[] AuthGetFileData(string fileUrl) { using (FileStream fs = new FileStream(fileUrl, FileMode.Open, FileAccess.Read)) { byte[] buffur = new byte[fs.Length]; fs.Read(buffur, 0, (int)fs.Length); return buffur; } }