大文件上传(引发WebException:连接被意外关闭)(Big files uploading

2019-07-29 09:36发布

更新

看帖子#3以下。

有必要为自动将文件上传到网络(不包括浏览器)。 主持人- 小文件存储系统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 - 附加PARAMS - 描述和密码,不一定施加)。 所以,我创建了一步模仿这样的行为步骤类:HttpWebRequest的页面的网址,申请所需的参数要求,形式请求字符串与StringBuilder的,并将其转换为字节数组,读取使用的FileStream文件,把所有的东西MemoryStream的,然后写它要求(带的代码大部分来自在CodeProject的一篇文章在那里文件上载到RAPIDSHARE主机)。 干净整洁,但...这似乎并没有工作:(。作为结果返回最初的上传页面,而不是一个带有链接的结果页面,我可以解析并呈现给用户......这里是一个上传的主要方法等级:

// 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(真/假)播放,甚至知道ServicePoint.Expect100Continue(假)未解决的问题。 即使在得到响应(在一个大的文件,它不会上传这么快的情况下,认为)没有帮助5秒超时。 内容类型“八位字节流”被选为目的上传任何文件(可以使用最流行的JPG / ZIP / RAR / DOC等一些开关,但是这一次似乎普遍)。 边界是由计时器滴答,不是什么大不了的随机生成的。 还有什么? :/我可以放弃,忘记了这一点,但我觉得我很接近解决, 然后忘掉它:P。 如果你需要在整个应用程序运行和调试 - 这里是(70KB,压缩C#2.0 VS2k8解决方案,无广告,无病毒):

@Mediafire @FileQube @FileDropper

Answer 1:

更新:不,没有重定向。

截图

阅读RFC2388几次,重写了代码,它终于摸索(我猜的麻烦是UTF-读尾部边界,而不是正确的7位ASCII)。 万岁? 没了:(。只有小文件转移,大的抛出“连接被意外关闭”。

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)增加的请求都超时和ReadWriteTimeout

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

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;
}


Answer 2:

“至于结果返回初始上传页面,提供前往目前没有结果页面我可以解析和用户......”

也许这就是的上传功能只是行为:即上传完成后,您可以上传另一个文件? 我认为你必须调用另一个网址的“浏览文件”页随机(我想这是一个你需要的)。


编辑 :其实,如果服务器发送一个“重定向”(HTTP 3XX),这件事情,浏览器必须处理,所以如果你在浏览器代替你自己的客户端应用程序的工作,你必须自己实现重定向。 这里的RFC获取更多信息。



Answer 3:

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



Answer 4:

在我的情况下,重复的文件名导致了问题也是如此。 我保存文件的设置在一个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">上传元件,这是用于限制文件的大小和其他过滤器很好的参考 。



文章来源: Big files uploading (WebException: The connection was closed unexpectedly)