C implements the HTTP method for uploading files

  • 2020-11-30 08:30:11
  • OfStack

This article gives an example of how C# implements the HTTP upload method. Share to everybody for everybody reference. Specific implementation methods are as follows:

Send the file code as follows:


/// <summary>
/// Http Upload a file
/// </summary>
public static string HttpUploadFile(string url, string path)
{
    // Set the parameters
    HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
    CookieContainer cookieContainer = new CookieContainer();
    request.CookieContainer = cookieContainer;
    request.AllowAutoRedirect = true;
    request.Method = "POST";
    string boundary = DateTime.Now.Ticks.ToString("X"); // Random divider
    request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
    byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
    byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");     int pos = path.LastIndexOf("\\");
    string fileName = path.Substring(pos + 1);     // Request header information
    StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));
    byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());     FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
    byte[] bArr = new byte[fs.Length];
    fs.Read(bArr, 0, bArr.Length);
    fs.Close();     Stream postStream = request.GetRequestStream();
    postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
    postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
    postStream.Write(bArr, 0, bArr.Length);
    postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
    postStream.Close();     // Send the request and get the corresponding response data
    HttpWebResponse response = request.GetResponse() as HttpWebResponse;
    // until request.GetResponse() The application then starts sending to the target page Post request
    Stream instream = response.GetResponseStream();
    StreamReader sr = new StreamReader(instream, Encoding.UTF8);
    // Return the results page ( html ) code
    string content = sr.ReadToEnd();
    return content;
}

The code to receive the file is as follows:


using System;
using System.Web; namespace SWX
{
    public partial class test2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpPostedFile file = Request.Files[0];
            file.SaveAs(MapPath("\\UploadFile\\" + file.FileName));
            Response.Write("Success\r\n");
        }
    }
}

Hopefully this article has helped you with your C# programming.


Related articles: