我们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 = 1000 * 120; 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, 0, postHeaderBytes.Length); // 将上传文件内容写入流 //每次上传4k 1024*4 byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)this.FileUpload1.PostedFile.InputStream.Length))]; int bytesRead = 0; while ((bytesRead = this.FileUpload1.PostedFile.InputStream.Read(buffer, 0, buffer.Length)) != 0) { requestStream.Write(buffer, 0, bytesRead); } // 将报文尾部写入流 requestStream.Write(boundaryBytes, 0, 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 > 0) { try { HttpPostedFile file = Request.Files[0]; string filePath = "D:\\test\\" + file.FileName; file.SaveAs(filePath); } catch { } } } }
时间: 2024-11-05 02:48:54