SoFunction
Updated on 2025-03-07

C# method to implement HTTP upload files


/// <summary>
/// Upload file by Http
/// </summary>
public static string HttpUploadFile(string url, string path)
{
// Set parameters
    HttpWebRequest request = (url) as HttpWebRequest;
    CookieContainer cookieContainer = new CookieContainer();
    = cookieContainer;
    = true;
    = "POST";
string boundary = ("X"); // Random divider
    = "multipart/form-data;charset=utf-8;boundary=" + boundary;
    byte[] itemBoundaryBytes = Encoding.("\r\n--" + boundary + "\r\n");
    byte[] endBoundaryBytes = Encoding.("\r\n--" + boundary + "--\r\n");

    int pos = ("\\");
    string fileName = (pos + 1);

//Request header information
    StringBuilder sbHeader = new StringBuilder(("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));
    byte[] postHeaderBytes = Encoding.(());

    FileStream fs = new FileStream(path, , );
    byte[] bArr = new byte[];
    (bArr, 0, );
    ();

    Stream postStream = ();
    (itemBoundaryBytes, 0, );
    (postHeaderBytes, 0, );
    (bArr, 0, );
    (endBoundaryBytes, 0, );
    ();

//Send a request and obtain corresponding response data
    HttpWebResponse response = () as HttpWebResponse;
//It is not until the () program starts sending Post requests to the destination web page
    Stream instream = ();
    StreamReader sr = new StreamReader(instream, Encoding.UTF8);
//Return the result web page (html) code
    string content = ();
    return content;
}