c# 使用WebRequest实现多文件上传

 更新时间:2021年03月18日 08:28:55   作者:陈开华  
这篇文章主要介绍了c# 使用WebRequest实现多文件上传的方法,帮助大家更好的理解和学习使用c#,感兴趣的朋友可以了解下

c#中通常使用HttpWebRequest进行HTTP网络请求,HttpWebRequest只对Http请求进行了最简单的封装。如果要利用Http协议实现多文件上传,则必须使用POST方法multipart/form-data格式。为了重复使用,我封装了几个方法,实现了多参数文件上传。

添加引用

使用WebRequest需要添加引用System.Web,否则引入出错。

参数封装

方便起见,我把请求参数进行了封装,代码如下:

namespace EasyHttp.Net.Core
{
  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;
    }
  }
}

KeyValue代表了广义的参数,可以是普通的键值对,也可以是文件参数。

多文件上传封装

public static void ExecuteMultipartRequest(HttpWebRequest request, List<KeyValue> nvc)
{
  Console.WriteLine(request.Headers);
  //  log.Debug(string.Format("Uploading {0} to {1}", file, url));
  string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
  byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

  HttpWebRequest wr = request;
  wr.ContentType = "multipart/form-data; boundary=" + boundary;
  wr.Method = "POST";
  wr.KeepAlive = true;
  wr.Credentials = System.Net.CredentialCache.DefaultCredentials;



  using (var rs = wr.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.FilePath, 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 = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
    rs.Write(trailer, 0, trailer.Length);

  }

}

使用

static void Main(string[] args)
    {
	var request = WebRequest.Create("http://localhost:8080/test/upload") as HttpWebRequest;
      List<KeyValue> keyValues = new List<KeyValue>();
      keyValues.Add(new KeyValue("key1","param1"));
      keyValues.Add(new KeyValue("key2", "param2"));
      keyValues.Add(new KeyValue("file","test1.png","image/png"));
      keyValues.Add(new KeyValue("file", "test2.png", "image/png"));

      EasyHttp.ExecuteMultipartRequest(request,keyValues);
    }

以上就是c# 使用WebRequest实现多文件上传的详细内容,更多关于c# 多文件上传的资料请关注脚本之家其它相关文章!

相关文章

  • C#调用python脚本的方法步骤(2种)

    C#调用python脚本的方法步骤(2种)

    这篇文章主要介绍了C#调用python脚本的方法步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-12-12
  • C#中子类调用父类的实现方法

    C#中子类调用父类的实现方法

    这篇文章主要介绍了C#中子类调用父类的实现方法,通过实例逐步分析了类中初始化构造函数的执行顺序问题,有助于加深对C#面向对象程序设计的理解,需要的朋友可以参考下
    2014-09-09
  • C#实现多线程的Web代理服务器实例

    C#实现多线程的Web代理服务器实例

    这篇文章主要介绍了C#实现多线程的Web代理服务器,涉及C#多线程代理服务器的实现技巧,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-07-07
  • C#飞行棋小程序设计分析

    C#飞行棋小程序设计分析

    这篇文章主要为大家设计分析了C#飞行棋小程序,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-09-09
  • treeview递归绑定的两种方法

    treeview递归绑定的两种方法

    这篇文章主要介绍了treeview递归绑定的两种方法,需要的朋友可以参考下
    2014-04-04
  • C#实现常见时间格式

    C#实现常见时间格式

    这篇文章介绍了C#实现常见时间格式的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-04-04
  • C#使用DevExpress中的SplashScreenManager控件实现启动闪屏和等待信息窗口

    C#使用DevExpress中的SplashScreenManager控件实现启动闪屏和等待信息窗口

    这篇文章介绍了C#使用DevExpress中的SplashScreenManager控件实现启动闪屏和等待信息窗口的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-05-05
  • C# wpf使用ListBox实现尺子控件的示例代码

    C# wpf使用ListBox实现尺子控件的示例代码

    本文主要介绍了C# wpf使用ListBox实现尺子控件的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-07-07
  • 不安装excel使用c#创建excel文件

    不安装excel使用c#创建excel文件

    这篇文章主要介绍了使用c#创建excel的示例,刚时给出了不安装excel也可创建excel的方法,需要的朋友可以参考下
    2014-02-02
  • C#实现十字链表的使用示例

    C#实现十字链表的使用示例

    十字链表是一种将数据存储在节点中的数据结构,每个节点包含两个指针,分别指向下一个节点和上一个节点,通过定义节点类和链表类,实现十字链表的创建、遍历、插入和删除等操作,本文就来实现一下
    2023-11-11

最新评论