SoFunction
Updated on 2025-03-02

c# Use WebRequest to implement multi-file upload

In c#, HttpWebRequest is usually used to perform HTTP network requests, and HttpWebRequest only encapsulates Http requests in the simplest way. If you want to use the Http protocol to achieve multi-file upload, you must use the POST method multipart/form-data format. For reuse, I encapsulated several methods and implemented multi-parameter file upload.

Add a reference

Use WebRequest to add a reference, otherwise an error will occur.

Parameter encapsulation

For convenience, I encapsulated the request parameters, the code is as follows:

namespace 
{
  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 represents a generalized parameter, which can be an ordinary key-value pair or a file parameter.

Multi-file upload encapsulation

public static void ExecuteMultipartRequest(HttpWebRequest request, List<KeyValue> nvc)
{
  ();
  //  (("Uploading {0} to {1}", file, url));
  string boundary = "---------------------------" + ("x");
  byte[] boundarybytes = ("\r\n--" + boundary + "\r\n");

  HttpWebRequest wr = request;
   = "multipart/form-data; boundary=" + boundary;
   = "POST";
   = true;
   = ;



  using (var rs = ())
  {
    // Normal parameter template    string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
    // Parameter template with file    string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
    foreach (KeyValue keyValue in nvc)
    {
      //If it is a normal parameter      if ( == null)
      {
        (boundarybytes, 0, );
        string formitem = (formdataTemplate, , );
        byte[] formitembytes = .(formitem);
        (formitembytes, 0, );
      }
      //If it is a file parameter, upload the file      else
      {
        (boundarybytes, 0, );

        string header = (headerTemplate, , , );
        byte[] headerbytes = .(header);
        (headerbytes, 0, );

        using (var fileStream = new FileStream(, , ))
        {
          byte[] buffer = new byte[4096];
          int bytesRead = 0;
          long total = 0;
          while ((bytesRead = (buffer, 0, )) != 0)
          {

            (buffer, 0, bytesRead);
            total += bytesRead;
          }
        }
      }
      
    }

    byte[] trailer = ("\r\n--" + boundary + "--\r\n");
    (trailer, 0, );

  }

}

use

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

      (request,keyValues);
    }

The above is the detailed content of c# using WebRequest to implement multi-file upload. For more information about c# multi-file upload, please pay attention to my other related articles!