2017-05-27 79 views
1

我正在研究ASP.NET框架2.0应用程序。在特定页面上,我提供了一个链接给用户。通过点击这个链接,一个窗口打开另一个aspx页面。这个页面实际上发送http请求到一个指向文件的第三方url(比如 - mirror urls从云下载文件)。 http响应在第一页使用response.write从用户点击链接返回给用户。使用ASP.Net Framework 2.0异步传输大文件

现在,我面对的问题是如果文件大小很低,那么它工作正常。但是,如果文件很大(即超过1 GB),那么我的应用程序将等待整个文件从URL下载。我曾尝试使用response.flush()将块数据发送给用户,但仍然无法使用应用程序,因为工作进程正忙于从第三方URL获取数据流。

是否有任何方式可以异步下载大文件,以便我的弹出窗口完成其执行(下载将在进行中),并且用户还可以在应用程序中并行执行其他活动。

感谢, Suvodeep

回答

1

使用Web客户端读取远程文件。您可以从WebClient获取流,而不是下载。把它放在while()循环中,并在Response流中推送来自WebClient流的字节。这样,您将同时进行异步下载和上传。

的HttpRequest例如:

private void WriteFileInDownloadDirectly() 
{ 
    //Create a stream for the file 
    Stream stream = null; 

    //This controls how many bytes to read at a time and send to the client 
    int bytesToRead = 10000; 

    // Buffer to read bytes in chunk size specified above 
    byte[] buffer = new byte[bytesToRead]; 

    // The number of bytes read 
    try 
    { 
     //Create a WebRequest to get the file 
     HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create("Remote File URL"); 

     //Create a response for this request 
     HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse(); 

     if (fileReq.ContentLength > 0) 
      fileResp.ContentLength = fileReq.ContentLength; 

     //Get the Stream returned from the response 
     stream = fileResp.GetResponseStream(); 

     // prepare the response to the client. resp is the client Response 
     var resp = HttpContext.Current.Response; 

     //Indicate the type of data being sent 
     resp.ContentType = "application/octet-stream"; 

     //Name the file 
     resp.AddHeader("Content-Disposition", $"attachment; filename=\"{ Path.GetFileName("Local File Path - can be fake") }\""); 
     resp.AddHeader("Content-Length", fileResp.ContentLength.ToString()); 

     int length; 
     do 
     { 
      // Verify that the client is connected. 
      if (resp.IsClientConnected) 
      { 
       // Read data into the buffer. 
       length = stream.Read(buffer, 0, bytesToRead); 

       // and write it out to the response's output stream 
       resp.OutputStream.Write(buffer, 0, length); 

       // Flush the data 
       resp.Flush(); 

       //Clear the buffer 
       buffer = new byte[bytesToRead]; 
      } 
      else 
      { 
       // cancel the download if client has disconnected 
       length = -1; 
      } 
     } while (length > 0); //Repeat until no data is read 
    } 
    finally 
    { 
     if (stream != null) 
     { 
      //Close the input stream 
      stream.Close(); 
     } 
    } 
} 

WebClient的流读取:

using (WebClient client = new WebClient()) 
{ 
    Stream largeFileStream = client.OpenRead("My Address"); 
} 
+0

Ваньо,上述HttpWebRequest的例子是完全一样的我目前的执行情况。我正在提供一个http url来创建httpwebrequest。但是问题是它通过while循环持续循环,直到1 GB文件结束,然后主进程退出while循环结束进程。 –

+0

如何异步使用Webclient,以便可以并行下载文件。请建议。 –

+0

更新了我的答案。这就是你如何从WebClient获取流。然后逻辑是一样的 - while循环和阅读块。 –