Upload files with HTTPWebrequest (multipart/form-data)

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

    For me, the following works (mostly inspirated from all of the following answers), I started from Elad's answer and modify/simplify things to match my need (remove not file form inputs, only one file, ...).

    Hope it can helps somebody :)

    (PS: I know that exception handling is not implemented and it assumes that it was written inside a class, so I may need some integration effort...)

    private void uploadFile()
        {
            Random rand = new Random();
            string boundary = "----boundary" + rand.Next().ToString();
            Stream data_stream;
            byte[] header = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"file_path\"; filename=\"" + System.IO.Path.GetFileName(this.file) + "\"\r\nContent-Type: application/octet-stream\r\n\r\n");
            byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
    
            // Do the request
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(MBF_URL);
            request.UserAgent = "My Toolbox";
            request.Method = "POST";
            request.KeepAlive = true;
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            data_stream = request.GetRequestStream();
            data_stream.Write(header, 0, header.Length);
            byte[] file_bytes = System.IO.File.ReadAllBytes(this.file);
            data_stream.Write(file_bytes, 0, file_bytes.Length);
            data_stream.Write(trailer, 0, trailer.Length);
            data_stream.Close();
    
            // Read the response
            WebResponse response = request.GetResponse();
            data_stream = response.GetResponseStream();
            StreamReader reader = new StreamReader(data_stream);
            this.url = reader.ReadToEnd();
    
            if (this.url == "") { this.url = "No response :("; }
    
            reader.Close();
            data_stream.Close();
            response.Close();
        }
    

提交回复
热议问题