httpwebRequest大文件上传

 1         private string HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc, object status) {
 2             //log.Debug(string.Format("Uploading {0} to {1}", file, url));
 3             string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
 4             byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
 5 
 6             HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
 7             wr.ContentType = "multipart/form-data; boundary=" + boundary;
 8             wr.Method = "POST";
 9             wr.KeepAlive = true;
10             wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
11             //wr.ContentLength
12             //wr.AllowWriteStreamBuffering = false;
13             //Stream rs = wr.GetRequestStream();
14             MemoryStream ms = new MemoryStream();
15 
16             string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
17             foreach (string key in nvc.Keys) {
18                 ms.Write(boundarybytes, 0, boundarybytes.Length);
19                 string formitem = string.Format(formdataTemplate, key, nvc[key]);
20                 byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
21                 ms.Write(formitembytes, 0, formitembytes.Length);
22             }
23             ms.Write(boundarybytes, 0, boundarybytes.Length);
24 
25             string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
26             string header = string.Format(headerTemplate, paramName, file, contentType);
27             byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
28             ms.Write(headerbytes, 0, headerbytes.Length);
29 
30             FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
31             byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
32 
33             wr.ContentLength = ms.Length + fileStream.Length + trailer.Length;
34             wr.AllowWriteStreamBuffering = false;
35             //设置超时时间  一定要设置 不然连接会被关闭 设置超时时间为1小时
36             wr.Timeout = 1000 * 3600;
37             wr.ReadWriteTimeout = 1000 * 3600;//当服务器5
38 
39             Stream rs = wr.GetRequestStream();
40             byte[] buffer = new byte[4096];
41             long count = 0;
42             ms.Position = 0;
43             while (true) {
44                 Array.Clear(buffer, 0, buffer.Length);
45                 
46                 int readlen = ms.Read(buffer, 0, buffer.Length);
47                 if (readlen <= 0) {
48                     break;
49                 }
50                 rs.Write(buffer, 0, readlen);
51                 //rs.Flush();
52             }
53 
54             int bytesRead = 0;
55             while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) >0) {
56                 count += bytesRead;
57                 rs.Write(buffer, 0, bytesRead);
58                 //rs.Flush();
59                 if (this.OnUploadProgressChanged != null) {
60                     try {
61                         this.OnUploadProgressChanged(status, ((double)count / (double)fileStream.Length)*100d);
62                     } catch (Exception ex) {
63 
64                     }
65                 }
66             }
67             fileStream.Close();
68 
69             //byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
70             rs.Write(trailer, 0, trailer.Length);
71             rs.Flush();
72             rs.Close();
73 
74             WebResponse wresp = null;
75             try {
76                 //System.Threading.Thread.Sleep(3000);
77                 wresp = wr.GetResponse();
78                 Stream stream2 = wresp.GetResponseStream();
79                 StreamReader reader2 = new StreamReader(stream2);
80                 return reader2.ReadToEnd();
81 
82                 //log.Debug(string.Format("File uploaded, server response is: {0}", reader2.ReadToEnd()));
83             } catch (Exception ex) {
84                 //log.Error("Error uploading file", ex);
85                 if (wresp != null) {
86                     wresp.Close();
87                     wresp = null;
88                 }
89                 return null;
90             } finally {
91                 wr = null;
92             }
93         }
contentType参数配置为application/octet-stream即可
重要参数
AllowWriteStreamBuffering = false
另超时时间必须设置得长一些,不然连接会被关闭 会抛出404错误


你可能感兴趣的:(httpwebRequest大文件上传)