2013-03-25 88 views
3

這個想法很簡單,我正在創建一項服務,用戶可以在另一個網站上放置一個文件的直接鏈接,我的程序將打開一個流到該遠程服務器並開始以字節讀取文件然後將每個讀取的字節返回給用戶。恢復下載

到目前爲止,我設法讓該工作,這裏是我的代碼

public void Index() 
    { 
     //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; //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("http://SOME-OTHER-SERVER.com/File.rar"); 


      //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.Response; 

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

      //Name the file 
      resp.AddHeader("Content-Disposition", "attachment; filename=\"" + "fle.rar" + "\""); 
      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(); 
      } 
     } 
    } 

當我去到我的網頁它下載完美,但問題是,如果我停止下載,不會再恢復。

我搜索了這個問題,發現有一個頭文件「Accept-Ranges」必須在連接中定義以支持簡歷。

所以我添加了標題,但沒有工作。

回答

13

處理Range Requests比這稍微複雜一些。一般來說,您需要在請求中處理RangeIf-Range標題,並且以Content-Range,DateETagContent-Location標題響應206部分內容

文章Range Requests in ASP.NET MVC – RangeFileResult詳細描述瞭如何創建一個ASP.NET MVC ActionResult範圍請求的支持。

在你的情況下,你還必須檢查對方(你使用的那一個是fileReq)是否支持範圍請求。如果是,你可以只請求所需的部分(並且最好將其緩存在本地),但如果不是,則需要獲取整個文件並尋找適當的位置(在這種情況下,你明確想要本地緩存場景)。

+0

非常感謝,這是一個完美的答案:) – BOSS 2013-10-15 13:12:54