简体   繁体   中英

HttpWebRequest upload file cause The operation has timed out WebException

I have been searching around for an answer but really don't know what cause my problem. I'm doing uploading a file to my server using HttpWebRequest, the scheme should be correct:
1. Compose multipart form data, boundary and trailer.
2. Set content length of request by combining length of form data, file.
3. Write directly to stream and keep track upload progress.

Here is the code I'm using:

        HttpWebRequest uploadWebRequest = Func.UploadFileCompose(string.Format("url?hash={0}", uploadKeys.hash), cookieCollection);
        string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
        string header = string.Format(headerTemplate, "video", Path.GetFileName(videoModel.DownloadedLocation), "video/mp4");
        byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
        byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + Func.boundary + "--\r\n");
        long totalBytes = 0;
        using(FileStream fileStream = new FileStream(videoModel.DownloadedLocation,FileMode.Open, FileAccess.Read))
        {
            totalBytes += headerbytes.Length;
            totalBytes += fileStream.Length;
            totalBytes += trailer.Length;
        }
        uploadWebRequest.ContentLength = totalBytes;

        using (Stream requestStream = uploadWebRequest.GetRequestStream())
        {
            requestStream.ReadTimeout = 10000;
            requestStream.WriteTimeout = 10000;

            //write header first
            requestStream.Write(headerbytes, 0, headerbytes.Length);

            using (FileStream fileStream = new FileStream(videoModel.DownloadedLocation, FileMode.Open, FileAccess.Read))
            {
                int bytesRead = 0;
                long bytesSent = 0;
                byte[] buffer = new byte[1024000];
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    bytesSent += bytesRead;
                    requestStream.Write(buffer, 0, bytesRead);
                    decimal percentage = (decimal)(bytesSent * 100) / (decimal)fileStream.Length;
                    if (Math.Round(percentage, 1) % 0.2M == 0)
                    {
                        Func.SetProgressStatus(lvStatus, "Uploaded: " + Math.Round(percentage, 1) + "%");
                    }
                }
            }
            //write trailer
            requestStream.Write(trailer, 0, trailer.Length);
        }
        string uploadResponseInStr = "";
        using (HttpWebResponse response = (HttpWebResponse)uploadWebRequest.GetResponse())
        {
            var encoding = ASCIIEncoding.ASCII;
            try
            {
                using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
                {
                    uploadResponseInStr = await reader.ReadToEndAsync();
                }
            }
            catch (Exception e1)
            {
                return null;
            }
        }

Tried to set

        req.KeepAlive = true; //true or false
        req.Timeout = 10000;
        req.ReadWriteTimeout = 10000;
        req.ProtocolVersion = HttpVersion.Version10; // 11 or 10

Does not help.
Thanks for help in advance. Really appreciate it!

Edit: Set DefaultConnectionLimit equal 1000 does not help.
The connection have been established but it only upload a few MB before exception raised

Solved.!
This request was missing boundary and the length was incorrect.
Also it is necessary to write boundary to stream too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM