Upload files with HTTPWebrequest (multipart/form-data)

后端 未结 21 2506
独厮守ぢ
独厮守ぢ 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:24

    I realize this is probably really late, but I was searching for the same solution. I found the following response from a Microsoft rep

    private void UploadFilesToRemoteUrl(string url, string[] files, string logpath, NameValueCollection nvc)
    {
    
        long length = 0;
        string boundary = "----------------------------" +
        DateTime.Now.Ticks.ToString("x");
    
    
        HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(url);
        httpWebRequest2.ContentType = "multipart/form-data; boundary=" +
        boundary;
        httpWebRequest2.Method = "POST";
        httpWebRequest2.KeepAlive = true;
        httpWebRequest2.Credentials = System.Net.CredentialCache.DefaultCredentials;
    
    
    
        Stream memStream = new System.IO.MemoryStream();
        byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
    
    
        string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
    
        foreach(string key in nvc.Keys)
        {
            string formitem = string.Format(formdataTemplate, key, nvc[key]);
            byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
            memStream.Write(formitembytes, 0, formitembytes.Length);
        }
    
    
        memStream.Write(boundarybytes,0,boundarybytes.Length);
    
        string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";
    
        for(int i=0;i

提交回复
热议问题