明天的明天 永远的永远 未知的一切 我与你一起承担 ??

是非成败转头空 青山依旧在 几度夕阳红 。。。
随笔 - 1277, 文章 - 0, 评论 - 214, 阅读 - 320万
  博客园  :: 首页  :: 管理
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

ASP.NET上传文件到远程服务器(HttpWebRequest)

Posted on   且行且思  阅读(1724)  评论(1编辑  收藏  举报
复制代码
/// <summary>
     /// 文件上传至远程服务器
     /// </summary>
     /// <param name="url">远程服务地址</param>
     /// <param name="postedFile">上传文件</param>
     /// <param name="parameters">POST参数</param>
     /// <param name="cookieContainer">cookie</param>
     /// <param name="output">远程服务器响应字符串</param>
     public static void HttpPostFile(string url,
                                     System.Web.HttpPostedFile postedFile,
                                     Dictionary<string, object> parameters,
                                     CookieContainer cookieContainer,
                                     ref string output)
     {
         //1>创建请求
         HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
         //2>Cookie容器
         request.CookieContainer = cookieContainer;
         request.Method = "POST";
         request.Timeout = 20000;
         request.Credentials = System.Net.CredentialCache.DefaultCredentials;
         request.KeepAlive = true;
 
         string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");//分界线
         byte[] boundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
 
         request.ContentType = "multipart/form-data; boundary=" + boundary; ;//内容类型
 
         //3>表单数据模板
         string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
 
         //4>读取流
         byte[] buffer = new byte[postedFile.ContentLength];
         postedFile.InputStream.Read(buffer, 0, buffer.Length);
 
         //5>写入请求流数据
         string strHeader = "Content-Disposition:application/x-www-form-urlencoded; name=\"{0}\";filename=\"{1}\"\r\nContent-Type:{2}\r\n\r\n";
         strHeader = string.Format(strHeader,
                                  "filedata",
                                  postedFile.FileName,
                                  postedFile.ContentType);
         //6>HTTP请求头
         byte[] byteHeader = System.Text.ASCIIEncoding.ASCII.GetBytes(strHeader);
         try
         {
             using (Stream stream = request.GetRequestStream())
             {
                 //写入请求流
                 if (null != parameters)
                 {
                     foreach (KeyValuePair<string, object> item in parameters)
                     {
                         stream.Write(boundaryBytes, 0, boundaryBytes.Length);//写入分界线
                         byte[] formBytes = System.Text.Encoding.UTF8.GetBytes(string.Format(formdataTemplate, item.Key, item.Value));
                         stream.Write(formBytes, 0, formBytes.Length);
                     }
                 }
                 //6.0>分界线============================================注意:缺少次步骤,可能导致远程服务器无法获取Request.Files集合
                 stream.Write(boundaryBytes, 0, boundaryBytes.Length);
                 //6.1>请求头
                 stream.Write(byteHeader, 0, byteHeader.Length);
                 //6.2>把文件流写入请求流
                 stream.Write(buffer, 0, buffer.Length);
                 //6.3>写入分隔流
                 byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
                 stream.Write(trailer, 0, trailer.Length);
                 //6.4>关闭流
                 stream.Close();
             }
             HttpWebResponse response = (HttpWebResponse)request.GetResponse();
             using (StreamReader reader = new StreamReader(response.GetResponseStream()))
             {
                 output = reader.ReadToEnd();
             }
             response.Close();
         }
         catch (Exception ex)
         {
             throw new Exception("上传文件时远程服务器发生异常!", ex);
         }
     }
复制代码

 

编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
历史上的今天:
2009-10-18 数据源改变后,BarChart组件的运动效果.
点击右上角即可分享
微信分享提示