一个网站中需要上传一个文件到另一个网站,可以使用HttpWebRequest或者WebClient。
但是WebClient需要首先上传文件到服务器,才能执行发送,不太符合我的需求,这里不再介绍。
通过HttpWebRequest发送的原理:
构建一个HttpWebRequest,通过FileUpload获取要上传的文件,通过字节流发送这个文件,另一个网站接收字节流,保存到服务器。
发送程序:
byte [] data = fileupload1.FileBytes; |
string fileName = fileupload1.FileName; |
string fileType = fileupload1.PostedFile.ContentType; |
string fileSize = data.Length.ToString(); |
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create( "http://localhost:8102/Default.aspx" ); |
myRequest.Method = "POST" ; |
myRequest.ContentType = fileType; |
myRequest.ContentLength = data.Length; |
myRequest.Headers.Add( "FileType" , Server.UrlEncode(fileType)); |
myRequest.Headers.Add( "FileSize" , fileSize); |
myRequest.Headers.Add( "FileName" , Server.UrlEncode(fileName)); |
using (Stream newStream = myRequest.GetRequestStream()) |
newStream.Write(data, 0, data.Length); |
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse(); |
StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8); |
string content = reader.ReadToEnd(); |
接收程序:
string fileName = Server.UrlDecode(Request.Headers[ "FileName" ].ToString()); |
string fileType = Server.UrlDecode(Request.Headers[ "FileType" ].ToString()); |
int fileSize = int .Parse(Request.Headers[ "FileSize" ].ToString()); |
byte [] bytes = Request.BinaryRead(fileSize); |
File.WriteAllBytes(Server.MapPath( "~/uploadfiles/" + fileName), bytes); |
Response.HeaderEncoding = System.Text.Encoding.UTF8; |
Response.Charset = "utf-8" ; |
Response.Write( "FileType:" + fileType + ";FileName:" + fileName + ";FileSize:" + fileSize); |
来源:http://blog.bossma.cn/dotnet/asp-net-httpwebrequest-upload-send-file/