2023-05-12 开启多语言插件支持……

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

asp.net 苏 demo 2705℃ 0评论

通过HttpWebRequest对象,创建POST请求,把客户端上传的文件流,上传到指定的服务器上!下面只是其中一种方式。我们也可以通过WebClienth、Ftp等多种方式实现该功能。

 

/// 
     /// 文件上传至远程服务器
     /// 
     /// 远程服务地址
     /// 上传文件
     /// POST参数
     /// cookie
     /// 远程服务器响应字符串
     public static void HttpPostFile(string url,
                                     System.Web.HttpPostedFile postedFile,
                                     Dictionary 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 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);
         }
     }

远程服务器处理上传请求

/// 
/// 上传方法
/// 
/// 
private void Upload(HttpContext context)
{
    TiKu.Common.LogUtil.Info(context.Request.ContentLength);
    HttpPostedFile file = context.Request.Files["filedata"];//获取上传文件
    if (null == file || file.ContentLength == 0)
    {
        context.Response.Write("{\"status\":\"0\",\"msg\":\"上传文件无效!\"}");
        return;
    }
    //上传文件大小(单位:字节)
    int ifileSize = file.ContentLength;
    string error = string.Empty/*错误消息*/,
           newfile = string.Empty/*上传文件名*/,
           uploadpath = "/upload/admin/"/*上传文件路径*/;
    if (TiKu.Common.UpfileTool.Upload(file,
                                      new string[3] { ".jpg", ".png", ".gif" },
                                      Helper.config.UploadMaxSize,
                                      uploadpath,
                                      ref newfile,
                                      ref error))
    {
        string cookie = (TiKu.Common.CookieUtil.GetCookieValue(TiKu.Common.Constants.ADMIN.COOKIE.COOKIE_SESSION));
        //context.Response.Write("{\"status\":\"1\",\"msg\":\"上传成功!\",\"path\":\"" + uploadpath + "\",\"filename\":\"" + newfile + "\",\"filesize\":\"" + ifileSize + "\"}");
        context.Response.Write(cookie);//这里测试远程请求Cookie
    }
    else
    {
        context.Response.Write("{\"status\":\"0\",\"msg\":\"" + error + "\"}");
    }
}

测试文件上传的方法

string strOutput = string.Empty;
           System.Net.CookieContainer cookie = new System.Net.CookieContainer();
           string strCookieHeader = TiKu.Common.Constants.ADMIN.COOKIE.COOKIE_SESSION + "=" + TiKu.Common.CookieUtil.GetCookieValue(TiKu.Common.Constants.ADMIN.COOKIE.COOKIE_SESSION);
           cookie.SetCookies(new Uri("http://static.xxx.com"), strCookieHeader);
           TiKu.Common.UpfileTool.HttpPostFile("http://static.xxxx.com/tool/upload_ajax.ashx",
                                                       FileUploader.PostedFile,
                                                       null,
                                                       cookie,
                                                       ref strOutput);
           Response.Write(strOutput);
打赏

转载请注明:苏demo的别样人生 » HttpWebRequest ASP.NET上传文件到远程服务器

   如果本篇文章对您有帮助,欢迎向博主进行赞助,赞助时请写上您的用户名。
支付宝直接捐助帐号oracle_lee@qq.com 感谢支持!
喜欢 (0)or分享 (0)