Upload files with HTTPWebrequest (multipart/form-data)

后端 未结 21 2575
独厮守ぢ
独厮守ぢ 2020-11-21 04:53

Is there any class, library or some piece of code which will help me to upload files with HTTPWebrequest?

Edit 2:

I do not

21条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-21 05:28

    Took the above and modified it accept some header values, and multiple files

        NameValueCollection headers = new NameValueCollection();
            headers.Add("Cookie", "name=value;");
            headers.Add("Referer", "http://google.com");
        NameValueCollection nvc = new NameValueCollection();
            nvc.Add("name", "value");
    
        HttpUploadFile(url, new string[] { "c:\\file1.txt", "c:\\file2.jpg" }, new string[] { "file", "image" }, new string[] { "application/octet-stream", "image/jpeg" }, nvc, headers);
    

    public static void HttpUploadFile(string url, string[] file, string[] paramName, string[] contentType, NameValueCollection nvc, NameValueCollection headerItems)
    {
        //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 = (HttpWebRequest)WebRequest.Create(url);
    
        foreach (string key in headerItems.Keys)
        {
            if (key == "Referer")
            {
                wr.Referer = headerItems[key];
            }
            else
            {
                wr.Headers.Add(key, headerItems[key]);
            }
        }
    
        wr.ContentType = "multipart/form-data; boundary=" + boundary;
        wr.Method = "POST";
        wr.KeepAlive = true;
        wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
    
        Stream rs = wr.GetRequestStream();
    
        string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
        foreach (string key in nvc.Keys)
        {
            rs.Write(boundarybytes, 0, boundarybytes.Length);
            string formitem = string.Format(formdataTemplate, key, nvc[key]);
            byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
            rs.Write(formitembytes, 0, formitembytes.Length);
        }
        rs.Write(boundarybytes, 0, boundarybytes.Length);
    
        string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
        string header = "";
    
        for(int i =0; i

提交回复
热议问题