LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

C# winform 上传文件 (多种方案)

admin
2017年3月22日 0:7 本文热度 6079

转:http://www.cnblogs.com/7in10/archive/2008/05/20/1203402.html

方案一:

注意:要开启虚拟目录的写入权限,要不然就报 403 错误

工作中用到winform上传文件(-_-!,很少用winform,搞了半天)
碰到一点问题,解决如下
1
501 为实现错误
解决方法:
先把IISWEB服务扩展中的WebDev打开
然后
IIS
站点添加MIME  txt类型常见的MIME类型如下
超文本标记语言文本 .html,.html text/html 
普通文本 .txt text/plain 
RTF
文本 .rtf application/rtf 
GIF
图形 .gif image/gif 
JPEG
图形 .ipeg,.jpg image/jpeg 
au
声音文件 .au audio/basic 
MIDI
音乐文件 mid,.midiaudio/midi,audio/x-midi 
RealAudio
音乐文件 .ra, .ram audio/x-pn-realaudio 
MPEG
文件 .mpg,.mpeg video/mpeg 
AVI
文件 .avi video/x-msvideo 
GZIP
文件 .gz application/x-gzip 
TAR
文件 .tar application/x-tar 
再然后
设置目标文件夹的可写性

http://www.cnblogs.com/Images/OutliningIndicators/None.gifusing System;
http://www.cnblogs.com/Images/OutliningIndicators/None.gif
using System.Collections.Generic;
http://www.cnblogs.com/Images/OutliningIndicators/None.gif
using System.Text;
http://www.cnblogs.com/Images/OutliningIndicators/None.gif
using System.Net;
http://www.cnblogs.com/Images/OutliningIndicators/None.gif
using System.IO;
http://www.cnblogs.com/Images/OutliningIndicators/None.gif
http://www.cnblogs.com/Images/OutliningIndicators/None.gif
namespace Common
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gifhttp://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif
{
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gifhttp://www.cnblogs.com/Images/OutliningIndicators/ContractedSubBlock.gif
///<summary>
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
/// winform形式的文件传输类
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif
///</summary>
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gifpublicclass WinFileTransporter
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gifhttp://www.cnblogs.com/Images/OutliningIndicators/ContractedSubBlock.gif{
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gifhttp://www.cnblogs.com/Images/OutliningIndicators/ContractedSubBlock.gif///<summary>
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
/// WebClient
上传文件至服务器,默认不自动改名
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
///</summary>
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
///<param name="fileNamePath">文件名,全路径格式</param>
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif
///<param name="uriString">服务器文件夹路径</param>
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gifpublicvoid UpLoadFile(string fileNamePath, string uriString)
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gifhttp://www.cnblogs.com/Images/OutliningIndicators/ContractedSubBlock.gif{
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif            UpLoadFile(fileNamePath, uriString, false);
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif        }
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gifhttp://www.cnblogs.com/Images/OutliningIndicators/ContractedSubBlock.gif///<summary>
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
/// WebClient
上传文件至服务器
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
///</summary>
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
///<param name="fileNamePath">文件名,全路径格式</param>
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
///<param name="uriString">服务器文件夹路径</param>
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif
///<param name="IsAutoRename">是否自动按照时间重命名</param>
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gifpublicvoid UpLoadFile(string fileNamePath, string uriString, bool IsAutoRename)
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gifhttp://www.cnblogs.com/Images/OutliningIndicators/ContractedSubBlock.gif{
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gifstring fileName = fileNamePath.Substring(fileNamePath.LastIndexOf("\\") + 1);
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gifstring NewFileName = fileName;
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gifif (IsAutoRename)
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gifhttp://www.cnblogs.com/Images/OutliningIndicators/ContractedSubBlock.gif{
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif                NewFileName = DateTime.Now.ToString("yyMMddhhmmss") + DateTime.Now.Millisecond.ToString() + fileNamePath.Substring(fileNamePath.LastIndexOf("."));
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif            }
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gifstring fileNameExt = fileName.Substring(fileName.LastIndexOf(".") + 1);
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gifif (uriString.EndsWith("/") == false) uriString = uriString + "/";
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif            uriString = uriString + NewFileName;
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif            Utility.LogWriter log = new Utility.LogWriter();
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif//log.AddLog(uriString, "Log");
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif            //log.AddLog(fileNamePath, "Log");
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gifhttp://www.cnblogs.com/Images/OutliningIndicators/ContractedSubBlock.gif
/**/
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gifhttp://www.cnblogs.com/Images/OutliningIndicators/ContractedSubBlock.gif///
创建WebClient实例
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif            WebClient myWebClient = new WebClient();
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif            myWebClient.Credentials = CredentialCache.DefaultCredentials;
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif// 
要上传的文件
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
            FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
//FileStream fs = OpenFile();
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
            BinaryReader r = new BinaryReader(fs);
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
byte[] postArray = r.ReadBytes((int)fs.Length);
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif            Stream postStream = myWebClient.OpenWrite(uriString, 
"PUT");
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
try
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gifhttp://www.cnblogs.com/Images/OutliningIndicators/ContractedSubBlock.gif
{
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
//使用UploadFile方法可以用下面的格式
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif                //myWebClient.UploadFile(uriString,"PUT",fileNamePath);
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif

http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
if (postStream.CanWrite)
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gifhttp://www.cnblogs.com/Images/OutliningIndicators/ContractedSubBlock.gif
{
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif                    postStream.Write(postArray, 
0, postArray.Length);
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif                    postStream.Close();
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif                    fs.Dispose();
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif                    log.AddLog(
"上传日志文件成功!""Log");
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif                }
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
else
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gifhttp://www.cnblogs.com/Images/OutliningIndicators/ContractedSubBlock.gif
{
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif                    postStream.Close();
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif                    fs.Dispose();
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif                    log.AddLog(
"上传日志文件失败,文件不可写!""Log");
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif                }
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif            }
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
catch (Exception err)
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gifhttp://www.cnblogs.com/Images/OutliningIndicators/ContractedSubBlock.gif
{
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif                postStream.Close();
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif                fs.Dispose();
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
//Utility.LogWriter log = new Utility.LogWriter();
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
                log.AddLog(err, "上传日志文件异常!""Log");
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
throw err;
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif            }
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
finally
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gifhttp://www.cnblogs.com/Images/OutliningIndicators/ContractedSubBlock.gif
{
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif                postStream.Close();
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif                fs.Dispose();
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif            }
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif        }
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gifhttp://www.cnblogs.com/Images/OutliningIndicators/ContractedSubBlock.gif
/**/
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gifhttp://www.cnblogs.com/Images/OutliningIndicators/ContractedSubBlock.gif
///<summary>
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
///下载服务器文件至客户端
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
///</summary>
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
///<param name="URL">被下载的文件地址,绝对路径</param>
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif
///<param name="Dir">另存放的目录</param>
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gifpublicvoid Download(string URL, string Dir)
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gifhttp://www.cnblogs.com/Images/OutliningIndicators/ContractedSubBlock.gif{
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif            WebClient client = new WebClient();
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gifstring fileName = URL.Substring(URL.LastIndexOf("\\") + 1);  //
被下载的文件名
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif

http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
string Path = Dir + fileName;   //另存为的绝对路径+文件名
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
            Utility.LogWriter log = new Utility.LogWriter();
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
try
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gifhttp://www.cnblogs.com/Images/OutliningIndicators/ContractedSubBlock.gif
{
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif                WebRequest myre = WebRequest.Create(URL);
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif            }
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
catch (Exception err)
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gifhttp://www.cnblogs.com/Images/OutliningIndicators/ContractedSubBlock.gif
{
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
//MessageBox.Show(exp.Message,"Error"); 
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
                log.AddLog(err, "下载日志文件异常!""Log");
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif            }
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
try
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gifhttp://www.cnblogs.com/Images/OutliningIndicators/ContractedSubBlock.gif
{
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif                client.DownloadFile(URL, fileName);
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif                FileStream fs = 
new FileStream(fileName, FileMode.Open, FileAccess.Read);
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif                BinaryReader r = 
new BinaryReader(fs);
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
byte[] mbyte = r.ReadBytes((int)fs.Length);
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif                FileStream fstr = 
new FileStream(Path, FileMode.OpenOrCreate, FileAccess.Write);
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif                fstr.Write(mbyte, 
0, (int)fs.Length);
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif                fstr.Close();
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif            }
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
catch (Exception err)
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gifhttp://www.cnblogs.com/Images/OutliningIndicators/ContractedSubBlock.gif
{
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
//MessageBox.Show(exp.Message,"Error");
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
                log.AddLog(err, "下载日志文件异常!""Log");
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif            }
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif        }
http://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif    }
http://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockEnd.gif}



方案二:

转:http://blog.csdn.net/walkinhill/archive/2004/08/28/87656.aspx

相信用ASP.NET写一个上传文件的网页,大家都会写,但是有没有人想过通过在WinForm中通过HTTP协议上传文件呢?

有些人说要向服务器端上传文件,用FTP协议不是很简单吗?效率又高,为什么还要使用HTTP协议那么麻烦呢?这里面有几个原因:

1FTP服务器的部署相对麻烦,还要设置权限,权限设置不对,还会惹来一系列的安全问题。

2)如果双方都还有防火墙,又不想开发FTP相关的一些端口时,HTTP就会大派用场,就像WEB Services能穿透防火墙一样。

3)其他的...,还在想呢...

但是使用HTTP也有他的一些问题,例如不能断点续传,大文件上传很难,速度很慢,所以HTTP协议上传的文件大小不应该太大。

说了这么多,原归正传,一般来说,在Winform里通过HTTP上传文件有几种可选的方法:

1)前面提到的Web Services,就是一种很好的方法,通过编写一个WebMethod,包含有 byte[] 类型的参数,然后调用Web Services的方法,文件内容就会以Base64编码传到服务器上,然后重新保存即可。

[WebMethod]
public void UploadFile(byte[] content,string filename){
          Stream sw = newStreamWriter(...);
          sw.Close();
}
当然,这种通过Base64编码的方法效率比较低,那么可以采用WSE,支持附件,并以2进制形式传送,效率会更高。
2)除了通过WebService,另外一种更简单的方法就是通过WebClient或者HttpWebRequest来模拟HTTPPOST动作来实现。这时候首先需要编写一个asp.net web form来响应上传,代码如下:
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs"AutoEventWireup="false" Inherits="UploadFileWeb.WebForm1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
<head>
 <title>WebForm1</title>
 <meta name="GENERATOR" Content="Microsoft VisualStudio .NET 7.1">
 <meta name="CODE_LANGUAGE" Content="C#">
 <meta name="vs_defaultClientScript"content="JavaScript">
 <meta name="vs_targetSchema" content="
http://schemas.microsoft.com/intellisense/ie5">
</head>
<body>
 <form id="Form1" method="post"runat="server">
 </form>
</body>
</html>

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespaceUploadFileWeb
{
/// <summary>
/// WebForm1 
的摘要说明。
/// </summary>
public class WebForm1 : System.Web.UI.Page
{
 private void Page_Load(object sender, System.EventArgs e)
 {
  // 
在此处放置用户代码以初始化页面
  foreach( string f in Request.Files.AllKeys)
  {
   HttpPostedFile file = Request.Files[f];
   file.SaveAs(@"D:\Temp\" + file.FileName);
  }
  if( Request.Params["testKey"] != null )
  {
   Response.Write(Request.Params["testKey"]);
  }
 }

 #regionWeb 窗体设计器生成的代码
 override protected void OnInit(EventArgs e)
 {
  //
  // CODEGEN: 
该调用是 ASP.NET Web 窗体设计器所必需的。
  //
  InitializeComponent();
  base.OnInit(e);
 }

 /// <summary>
 /// 
设计器支持所需的方法 -不要使用代码编辑器修改
 /// 
此方法的内容。
 /// </summary>
 private void InitializeComponent()
 {    
  this.Load += new System.EventHandler(this.Page_Load);
 }
 #endregion
}
}

其实这个页面跟我们平常写的asp.net上传文件代码是一样的,在Web 页的Request对象中包含有Files这个对象,里面就包含了通过POST方式上传的所有文件的信息,这时所需要做的就是调用Request.Files[i].SaveAs方法。

但是怎么让才能在WinForm里面模拟想Web Form POST 数据呢?System.Net命名空间里面提供了两个非常有用的类,一个是WebClient,另外一个是HttpWebRequest类。如果我们不需要通过代理服务器来上传文件,那么非常简单,只需要简单的调用WebClient.UploadFile方法就能实现上传文件:

private void button1_Click(object sender, System.EventArgs e)
 {
  WebClient myWebClient = new WebClient();

  myWebClient.UploadFile("
http://localhost/UploadFileWeb/WebForm1.aspx","POST",@"D:\Temp\Java\JavaStart\JavaStart2.exe");
      }

是不是觉得很简单呢?确实就这么简单。

但是如果要通过代理服务器上传又怎么办呢?那就需要使用到HttpWebRequest,但是该类没有Upload方法,但是幸运的是我们通过Reflector反编译了WebClient.UploadFile方法后,我们发现其内部也是通过WebRequest来实现的,代码如下:
public byte[] UploadFile(string address,string method, string fileName)
{
     string text1;
     string text2;
     WebRequest request1;
     string text3;
     byte[] buffer1;
     byte[] buffer2;
     long num1;
     byte[] buffer3;
     int num2;
     WebResponse response1;
     byte[] buffer4;
     DateTime time1;
     long num3;
     string[] textArray1;
     FileStream stream1 = null;
     try
     {
           fileName =Path.GetFullPath(fileName);
           time1 =DateTime.Now;
           num3 =time1.Ticks;
           text1 ="---------------------" + num3.ToString("x");
           if (this.m_headers== null)
           {
                this.m_headers = new WebHeaderCollection();
           }
           text2 =this.m_headers["Content-Type"];
           if (text2 !=null)
           {
                if (text2.ToLower(CultureInfo.InvariantCulture).StartsWith("multipart/"))
                {
                      throw new WebException(SR.GetString("net_webclient_Multipart"));
                }
           }
           else
           {
                text2 = "application/octet-stream";
           }
          this.m_headers["Content-Type"] = "multipart/form-data;boundary=" + text1;
          this.m_responseHeaders = null;
           stream1 =new FileStream(fileName, FileMode.Open, FileAccess.Read);
           request1 =WebRequest.Create(this.GetUri(address));
          request1.Credentials = this.Credentials;
          this.CopyHeadersTo(request1);
          request1.Method = method;
           textArray1 =new string[7];
          textArray1[0] = "--";
          textArray1[1] = text1;
          textArray1[2] = "\r\nContent-Disposition: form-data;name=\"file\"; filename=\"";
          textArray1[3] = Path.GetFileName(fileName);
          textArray1[4] = "\"\r\nContent-Type: ";
           textArray1[5]= text2;
          textArray1[6] = "\r\n\r\n";
           text3 =string.Concat(textArray1);
           buffer1 =Encoding.UTF8.GetBytes(text3);
           buffer2 =Encoding.ASCII.GetBytes("\r\n--" + text1 + "\r\n");
           num1 =9223372036854775807;
           try
           {
                num1 = stream1.Length;
                request1.ContentLength = ((num1 + ((long) buffer1.Length)) + ((long)buffer2.Length));
           }
           catch
           {
           }
           buffer3 =new byte[Math.Min(((int) 8192), ((int) num1))];
           using(Stream stream2 = request1.GetRequestStream())
           {
                stream2.Write(buffer1, 0, buffer1.Length);
                do
                {
                      num2 = stream1.Read(buffer3, 0, buffer3.Length);
                      if (num2 != 0)
                      {
                            stream2.Write(buffer3, 0, num2);
                      }
                }
                while ((num2 != 0));
                stream2.Write(buffer2, 0, buffer2.Length);
           }
          stream1.Close();
           stream1 =null;
           response1 =request1.GetResponse();
          this.m_responseHeaders = response1.Headers;
           returnthis.ResponseAsBytes(response1);
     }
     catch (Exception exception1)
     {
           if (stream1!= null)
           {
                stream1.Close();
                stream1 = null;
           }
           if((exception1 is WebException) || (exception1 is SecurityException))
           {
                throw;
           }
           throw newWebException(SR.GetString("net_webclient"), exception1);
     }
     return buffer4;
}


在这段代码里面其实最关键的就是如何模拟POST请求,通过分析代码和监视HTTP,我们可以发现模拟的POST格式如下:

-----------------------8c64f47716481f0  //
时间戳

Content-Disposition:form-data; name="file"; filename="a.txt"  //文件名

Content-Type: application/octet-stream


该文章在 2017/3/22 0:07:35 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2024 ClickSun All Rights Reserved