1.整理HttpWebRequest上傳多文件和多參數。較上一個版本,更具普適性和簡易型。注意(服務方web.config中要配置)這樣就可以上傳大文件了
<system.webServer> <requestFiltering> <requestLimits maxAllowedContentLength="4294967295" /> </requestFiltering> </system.webServer> <system.web> <httpRuntime maxRequestLength="2048000"/> </system.web>
2.HttpWebRequest的封裝
/// <summary> /// Http上傳文件類 - HttpWebRequest封裝 /// </summary> public class HttpUploadClient { public static string ExecuteMultipartRequest(string url, List<KeyValue> nvc) { string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x"); byte[] boundarybytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n"); HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url, UriKind.RelativeOrAbsolute)); webRequest.Method = "POST"; webRequest.Timeout = 1800000; webRequest.ContentType = "multipart/form-data; boundary=" + boundary; webRequest.KeepAlive = true; webRequest.Credentials = System.Net.CredentialCache.DefaultCredentials; using (var rs = webRequest.GetRequestStream()) { // 普通參數模板 string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}"; //帶文件的參數模板 string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n"; foreach (KeyValue keyValue in nvc) { //如果是普通參數 if (keyValue.FilePath == null) { rs.Write(boundarybytes, 0, boundarybytes.Length); string formitem = string.Format(formdataTemplate, keyValue.Key, keyValue.Value); byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem); rs.Write(formitembytes, 0, formitembytes.Length); } //如果是文件參數,則上傳文件 else { rs.Write(boundarybytes, 0, boundarybytes.Length); string header = string.Format(headerTemplate, keyValue.Key, keyValue.Value, keyValue.ContentType); byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header); rs.Write(headerbytes, 0, headerbytes.Length); using (var fileStream = new FileStream(keyValue.FilePath, FileMode.Open, FileAccess.Read)) { byte[] buffer = new byte[4096]; int bytesRead = 0; long total = 0; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { rs.Write(buffer, 0, bytesRead); total += bytesRead; } } } } byte[] trailer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); rs.Write(trailer, 0, trailer.Length); rs.Close(); } // 獲取響應 using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse()) { using (StreamReader reader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8)) { string body = reader.ReadToEnd(); reader.Close(); return body; } } }
3.參數封裝(支持普通參數和多文件)
public class KeyValue { public string Key; public string Value; public string FilePath; public string ContentType = "*/*"; public KeyValue(string key, string value, string filePath, string contentType) { Key = key; Value = value; FilePath = filePath; ContentType = contentType; } public KeyValue() { } public KeyValue(string key, string value, string filePath) { Key = key; Value = value; FilePath = filePath; } public KeyValue(string key, string value) { Key = key; Value = value; } }
4.調用示例
List<KeyValue> keyValues = new List<KeyValue>(); keyValues.Add(new KeyValue("key1", "12_423232523")); keyValues.Add(new KeyValue("key2", " 1 2 3")); keyValues.Add(new KeyValue("file1", "1.img", @"C:\臨時\tempDB\1.img")); keyValues.Add(new KeyValue("file2", "2.xls", @"C:\臨時\tempDB\2.xls")); HttpUploadClient.ExecuteMultipartRequest(url, keyValues);
5.服務接收方示例
for (int i = 0; i < HttpContext.Current.Request.Files.Count; i++) { HttpPostedFile file = HttpContext.Current.Request.Files[i]; file.SaveAs(""+file.FileName); } string Params = HttpContext.Current.Request.Form["key1"];