Upload files with HTTPWebrequest (multipart/form-data)

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

    Based on the code provided above I added support for multiple files and also uploading a stream directly without the need to have a local file.

    To upload files to a specific url including some post params do the following:

    RequestHelper.PostMultipart(
        "http://www.myserver.com/upload.php", 
        new Dictionary() {
            { "testparam", "my value" },
            { "file", new FormFile() { Name = "image.jpg", ContentType = "image/jpeg", FilePath = "c:\\temp\\myniceimage.jpg" } },
            { "other_file", new FormFile() { Name = "image2.jpg", ContentType = "image/jpeg", Stream = imageDataStream } },
        });
    

    To enhance this even more one could determine the name and mime type from the given file itself.

    public class FormFile 
    {
        public string Name { get; set; }
    
        public string ContentType { get; set; }
    
        public string FilePath { get; set; }
    
        public Stream Stream { get; set; }
    }
    
    public class RequestHelper
    {
    
        public static string PostMultipart(string url, Dictionary parameters) {
    
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
    
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            request.Method = "POST";
            request.KeepAlive = true;
            request.Credentials = System.Net.CredentialCache.DefaultCredentials;
    
            if(parameters != null && parameters.Count > 0) {
    
                using(Stream requestStream = request.GetRequestStream()) {
    
                    foreach(KeyValuePair pair in parameters) {
    
                        requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                        if(pair.Value is FormFile) {
                            FormFile file = pair.Value as FormFile;
                            string header = "Content-Disposition: form-data; name=\"" + pair.Key + "\"; filename=\"" + file.Name + "\"\r\nContent-Type: " + file.ContentType + "\r\n\r\n";
                            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(header);
                            requestStream.Write(bytes, 0, bytes.Length);
                            byte[] buffer = new byte[32768];
                            int bytesRead;
                            if(file.Stream == null) {
                                // upload from file
                                using(FileStream fileStream = File.OpenRead(file.FilePath)) {
                                    while((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                                        requestStream.Write(buffer, 0, bytesRead);
                                    fileStream.Close();
                                }
                            }
                            else {
                                // upload from given stream
                                while((bytesRead = file.Stream.Read(buffer, 0, buffer.Length)) != 0)
                                    requestStream.Write(buffer, 0, bytesRead);
                            }
                        }
                        else {
                            string data = "Content-Disposition: form-data; name=\"" + pair.Key + "\"\r\n\r\n" + pair.Value;
                            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data);
                            requestStream.Write(bytes, 0, bytes.Length);
                        }
                    }
    
                    byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
                    requestStream.Write(trailer, 0, trailer.Length);
                    requestStream.Close();
                }
            }
    
            using(WebResponse response = request.GetResponse()) {
                using(Stream responseStream = response.GetResponseStream())
                using(StreamReader reader = new StreamReader(responseStream))
                    return reader.ReadToEnd();
            }
    
    
        }
    }
    

提交回复
热议问题