大文件上传(WebException:连接意外关闭)

时间:2009-06-29 22:50:06

标签: c# .net file upload httpwebrequest

已更新

请参阅下面的帖子#3

需要自动将文件上传到网络(无需浏览器)。主持人 - Mini File Host v1.2(如果这很重要)。没有在文档中找到特定的api,所以最初我在Firebug中嗅探浏览器请求如下:

Params : do
Value : verify
POST /upload.php?do=verify HTTP/1.1
Host: webfile.ukrwest.net
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; ru; rv:1.9.0.8) Gecko/2009032609 Firefox/3.0.8 (.NET CLR 4.0.20506)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: ru,en-us;q=0.7,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: windows-1251,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://filehoster.awardspace.com/index.php
Content-Type: multipart/form-data; boundary=---------------------------27368237179714
Content-Length: 445

-----------------------------27368237179714
Content-Disposition: form-data; name="upfile"; filename="Test.file"
Content-Type: application/octet-stream

12345678901011121314151617sample text
-----------------------------27368237179714
Content-Disposition: form-data; name="descr"


-----------------------------27368237179714
Content-Disposition: form-data; name="pprotect"


-----------------------------27368237179714--

这里我们可以看到参数,标题,内容类型和信息块(1 - 文件名和类型,2 - 文件内容,3 - 其他参数 - 描述和密码,不一定适用)。 所以我创建了一个一步一步模拟这种行为的类:在url上使用HttpWebRequest,使用所需的参数来请求,使用StringBuilder形成请求字符串并将它们转换为字节数组,使用FileStream读取文件,将所有内容放入MemoryStream然后将其写入请求(从CodeProject的一篇文章中获取代码的主要部分,它将文件上传到Rapidshare主机)。  整洁,但......它似乎不起作用:(。结果它返回初始上传页面,而不是带有我可以解析并呈现给用户的链接的结果页面...... 以下是Uploader类的主要方法:

// Step 1 - request creation 
 private HttpWebRequest GetWebrequest(string boundary)
 {
            Uri uri = new Uri("http://filehoster.awardspace.com/index.php?do=verify");
            System.Net.HttpWebRequest httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
            httpWebRequest.CookieContainer = _cookies;
            httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;
            httpWebRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.2; ru; rv:1.9.0.8) Gecko/2009032609 Firefox/3.0.8 (.NET CLR 4.0.20506)";
            httpWebRequest.Referer = "http://filehoster.awardspace.com/index.php";
            httpWebRequest.Method = "POST";
            httpWebRequest.KeepAlive = true;
            httpWebRequest.Timeout = -1;
            //httpWebRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            httpWebRequest.Headers.Add("Accept-Charset", "windows-1251,utf-8;q=0.7,*;q=0.7");
            httpWebRequest.Headers.Add("Accept-Encoding", "gzip,deflate");
            httpWebRequest.Headers.Add("Accept-Language", "ru,en-us;q=0.7,en;q=0.3");
            //httpWebRequest.AllowAutoRedirect = true;
            //httpWebRequest.ProtocolVersion = new Version(1,1);
            //httpWebRequest.SendChunked = true;
            //httpWebRequest.Headers.Add("Cache-Control", "no-cache");
            //httpWebRequest.ServicePoint.Expect100Continue = false;
            return httpWebRequest;
}
// Step 2 - first message part (before file contents)
private string GetRequestMessage(string boundary, string FName, string description, string password)
{    
            System.Text.StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append("--");
            stringBuilder.Append(boundary);
            stringBuilder.Append("\r\n");
            stringBuilder.Append("Content-Disposition: form-data; name=\"");
            stringBuilder.Append("upfile");
            stringBuilder.Append("\"; filename=\"");
            stringBuilder.Append(FName);
            stringBuilder.Append("\"");
            stringBuilder.Append("\r\n");
            stringBuilder.Append("Content-Type: application/octet-stream");
            stringBuilder.Append("\r\n");
            return stringBuilder.ToString();
}
// Step 4 - additional request parameters. Step 3 - reading file is in method below
private string GetRequestMessageEnd(string boundary)
{    
            System.Text.StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append(boundary);
            stringBuilder.Append("\r\n");
            stringBuilder.Append("Content-Disposition: form-data; name=\"descr\"");
            stringBuilder.Append("\r\n");
            stringBuilder.Append("\r\n");
            stringBuilder.Append("Default description");
            stringBuilder.Append("\r\n");
            stringBuilder.Append(boundary);
            stringBuilder.Append("\r\n");
            stringBuilder.Append("Content-Disposition: form-data; name=\"pprotect\"");
            stringBuilder.Append("\r\n");
            stringBuilder.Append("\r\n");
            stringBuilder.Append("");
            stringBuilder.Append("\r\n");
            stringBuilder.Append(boundary);
            stringBuilder.Append("--");
            //stringBuilder.Append("\r\n");
            //stringBuilder.Append(boundary);
            //stringBuilder.Append("\r\n");
            return stringBuilder.ToString();
}
// Main method
public string ProcessUpload(string FilePath, string description, string password)
{
            // Chosen file information
            FileSystemInfo _file = new FileInfo(FilePath);
            // Random boundary generation
            DateTime dateTime2 = DateTime.Now;
            long l2 = dateTime2.Ticks;
            string _generatedBoundary = "----------" + l2.ToString("x");
            // Web request creation
            System.Net.HttpWebRequest httpWebRequest = GetWebrequest(_generatedBoundary);
            // Main app block - form and send request
            using (System.IO.FileStream fileStream = new FileStream(_file.FullName, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                byte[] bArr1 = Encoding.ASCII.GetBytes("\r\n--" + _generatedBoundary + "\r\n");
                // Generating pre-content post message
                string firstPostMessagePart = GetRequestMessage(_generatedBoundary, _file.Name, description, password);
                // Writing first part of request
                byte[] bArr2 = Encoding.UTF8.GetBytes(firstPostMessagePart);
                Stream memStream = new MemoryStream();
                memStream.Write(bArr1, 0, bArr1.Length);
                memStream.Write(bArr2, 0, bArr2.Length);
                // Writing file
                byte[] buffer = new byte[1024];
                int bytesRead = 0;
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    memStream.Write(buffer, 0, bytesRead);
                }
                // Generating end of a post message
                string secondPostMessagePart = GetRequestMessageEnd(_generatedBoundary);
                byte[] bArr3 = Encoding.UTF8.GetBytes(secondPostMessagePart);
                memStream.Write(bArr3, 0, bArr3.Length);
                // Preparing to send
                httpWebRequest.ContentLength = memStream.Length;
                fileStream.Close();

                Stream requestStream = httpWebRequest.GetRequestStream();

                memStream.Position = 0;
                byte[] tempBuffer = new byte[memStream.Length];
                memStream.Read(tempBuffer, 0, tempBuffer.Length);
                memStream.Close();
                // Sending request
                requestStream.Write(tempBuffer, 0, tempBuffer.Length);
                requestStream.Close();
            }
            // Delay (?)
            System.Threading.Thread.Sleep(5000);
            // Getting response
            string strResponse = "";
            using (Stream stream = httpWebRequest.GetResponse().GetResponseStream())
            using (StreamReader streamReader = new StreamReader(stream/*, Encoding.GetEncoding(1251)*/))
            {
                strResponse = streamReader.ReadToEnd();
            }
            return strResponse;
}

使用ProtocolVersion(1.0,1.1),AllowAutoRedirect(true / false)播放,即使已知的ServicePoint.Expect100Continue(false)也没有解决问题。即使是在获得响应之前的5秒超时(考虑到大文件没有上传如此之快)也无济于事。 内容类型“octet-stream”被选择用于上传任何文件(可以使用一些开关用于最流行的jpg / zip / rar / doc等,但那个似乎是通用的)。边界是从计时器滴答中随机生成的,并不是什么大问题。还有什么? :/ 我可以放弃并忘记这一点,但我觉得我很接近解决,然后忘记它:P。 如果你需要整个应用程序来运行和调试 - 这里是(70kb,压缩C#2.0 VS2k8解决方案,没有广告,没有病毒):

@Mediafire @FileQube @FileDropper

4 个答案:

答案 0 :(得分:10)

更新:不,没有重定向。

screenshot

阅读RFC2388几次,重写代码并最终工作(我猜麻烦是在utf-read尾部边界而不是正确的7位ascii)。万岁? Nope :(。只传输小文件,大文件投掷“连接意外关闭”。

System.Net.WebException was unhandled by user code
  Message="The underlying connection was closed: The connection was closed unexpectedly."
  Source="Uploader"
  StackTrace:
   at Uploader.Upload.ProcessUpload(String FilePath, String description, String password) in F:\MyDocuments\Visual Studio 2008\Projects\Uploader\Uploader.cs:line 96
   at Uploader.Form1.backgroundWorker1_DoWork(Object sender, DoWorkEventArgs e) in F:\MyDocuments\Visual Studio 2008\Projects\Uploader\Form1.cs:line 45
   at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument) 

我知道这是.net堆栈的错误,并且存在一些解决方案:

1)增加请求的Timeout和ReadWriteTimeout

2)分配request.KeepAlive = false和System.Net.ServicePointManager.Expect100Continue = false

3)将ProtocolVersion设置为1.0 但在我的案例中,他们或其中任何一人都没有完全帮助。有什么想法吗?

编辑 - 源代码:

// .. request created, required params applied
httpWebRequest.ProtocolVersion = HttpVersion.Version10; // fix 1
httpWebRequest.KeepAlive = false; // fix 2
httpWebRequest.Timeout = 1000000000; // fix 3
httpWebRequest.ReadWriteTimeout = 1000000000; // fix 4
// .. request processed, data written to request stream
string strResponse = "";            
try
{
    using (WebResponse httpResponse = httpWebRequest.GetResponse()) // error here
        {
            using (Stream responseStream = httpResponse.GetResponseStream())
            {
                using (StreamReader streamReader = new StreamReader(responseStream))
                    {
                        strResponse = streamReader.ReadToEnd();
                    }
                }
            }
        }
catch (WebException exception)
{
    throw exception;
}

答案 1 :(得分:0)

“结果它返回初始上传页面,而不是带有我可以解析并呈现给用户的链接的结果页面......”

也许这只是上传功能的行为:上传完成后,你可以上传另一个文件? 我想你必须为“浏览文件”页面调用另一个URL(我想这是你需要的那个)。


编辑:实际上,如果服务器发送“重定向”(http 3xx),这是浏览器必须处理的内容,因此如果您正在使用自己的客户端应用程序而不是浏览器,你必须自己实现重定向。这里有rfc以获取更多信息。

答案 2 :(得分:0)

尝试在Web.config中设置httpRuntime元素的maxRequestLength属性。

答案 3 :(得分:0)

就我而言,重复的文件名也会导致问题。我将文件的设置保存在xml文件中,但名称设置相互重复。

      <field name="StillImage">
        <prefix>isp_main_</prefix>
        <suffix>308</suffix>
        <width>1080</width>
        <height>1080</height>
      </field>
      <field name="ThumbnailImage">
        <prefix>isp_thumb_</prefix> // pay attention to this
        <suffix>308</suffix>
        <width>506</width>
        <height>506</height>
      </field>
      <field name="Logo">
        <prefix>isp_thumb_</prefix> // and this
        <suffix>306</suffix>
        <width>506</width>
        <height>506</height>
      </field>

而且,在另一个案例中我,问题出在文件长度。请检查服务器上允许的文件大小。在您的脚本中,请检查此部分:

dataStream.Write(filesBytesArray, 0, filesBytesArray.Length);
dataStream.Close();

如果您不知道,只需在前端部分限制文件上传大小即。 HTML <input type="file">上传元素,这是good reference for limiting file size and other filter