关于HttpWebRequest上传文件

时间:2023-03-10 01:40:00
关于HttpWebRequest上传文件

我们web 操作离不开 http请求响应 HttpWebRequest上传文件也是一样的道理

下面码一些代码:

  

 private void UploadFile(string strRequestUri, string strCookie, string filename)
{
// 初始化HttpWebRequest
HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(strRequestUri); // 封装Cookie
Uri uri = new Uri(strRequestUri);
Cookie cookie = new Cookie("Name", strCookie);
CookieContainer cookies = new CookieContainer();
cookies.Add(uri, cookie);
httpRequest.CookieContainer = cookies; // 生成时间戳
string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");
byte[] boundaryBytes = Encoding.ASCII.GetBytes(string.Format("\r\n--{0}--\r\n", strBoundary)); // 填报文类型
httpRequest.Method = "Post";
httpRequest.Timeout = * ;
httpRequest.ContentType = "multipart/form-data; boundary=" + strBoundary; // 封装HTTP报文头的流
StringBuilder sb = new StringBuilder();
sb.Append("--");
sb.Append(strBoundary);
sb.Append(Environment.NewLine);
sb.Append("Content-Disposition: form-data; name=\"");
sb.Append("file");
sb.Append("\"; filename=\"");
sb.Append(filename);
sb.Append("\"");
sb.Append(Environment.NewLine);
sb.Append("Content-Type: ");
sb.Append("multipart/form-data;");
sb.Append(Environment.NewLine);
sb.Append(Environment.NewLine);
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sb.ToString()); // 计算报文长度
long length = postHeaderBytes.Length + this.FileUpload1.PostedFile.InputStream.Length + boundaryBytes.Length;
httpRequest.ContentLength = length; // 将报文头写入流
Stream requestStream = httpRequest.GetRequestStream();
requestStream.Write(postHeaderBytes, , postHeaderBytes.Length); // 将上传文件内容写入流 //每次上传4k 1024*4
byte[] buffer = new Byte[checked((uint)Math.Min(, (int)this.FileUpload1.PostedFile.InputStream.Length))];
int bytesRead = ; while ((bytesRead = this.FileUpload1.PostedFile.InputStream.Read(buffer, , buffer.Length)) != )
{
requestStream.Write(buffer, , bytesRead);
} // 将报文尾部写入流
requestStream.Write(boundaryBytes, , boundaryBytes.Length);
// 关闭流
requestStream.Close();
} protected void btnRelease_Click(object sender, EventArgs e)
{
this.UploadFile(@"http://localhost/Qpdfgesigntest/SystemManager/WebsitePublishing/test.aspx", "yangtest", this.FileUpload1.PostedFile.FileName);
}
public partial class SystemManager_WebsitePublishing_test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Files.Count > )
{
try
{
HttpPostedFile file = Request.Files[];
string filePath = "D:\\test\\" + file.FileName;
file.SaveAs(filePath); }
catch
{ }
}
}
}