HttpWebRequest上传多文件和多参数——整理
1.整理HttpWebRequest上传多文件和多参数。较上一个版本,更具普适性和简易型。注意(服务方web.config中要配置)这样就可以上传大文件了
1 2 3 4 5 6 7 8 | <system.webServer> <requestFiltering> <requestLimits maxAllowedContentLength= "4294967295" /> </requestFiltering> </system.webServer> <system.web> <httpRuntime maxRequestLength= "2048000" /> </system.web> |
2.HttpWebRequest的封装
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | /// <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.参数封装(支持普通参数和多文件)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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.调用示例
1 2 3 4 5 6 | 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.服务接收方示例
1 2 3 4 5 6 | 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" ]; |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构