一个网站中需要上传一个文件到另一个网站,可以使用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()) ??????? { ??????????? // Send the data. ??????????? newStream.Write(data, 0, data.Length); ??????????? newStream.Close(); ??????? } ??????? // Get response ??????? 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);
关键字: HttpWebRequest
发表评论
相关文章
国内AI资源汇总,AI聊天、AI绘画、AI写作、AI视频、AI设计、AI编程、AI音乐等,国内顺畅访问,无需科学上网。
扫码或点击进入:萤火AI大全
文章分类
最新评论