2015-11-10 78 views
0

那麼,下面是我的代碼,它涉及到一個zip文件的下載。所有的事情都可以正常工作,但是當有一個正在進行的下載請求時,它無法下載文件。MVC Web Api 2:如何允許文件的並行下載

public class ZipController : ApiController 
    { 
     [System.Web.Http.AcceptVerbs("GET", "POST")] 
     [System.Web.Http.HttpGet] 
     public HttpResponseMessage DownloadFile() 
     { 
      var zipPath = ConfigurationManager.AppSettings["FilePath"]; 
      var result = new HttpResponseMessage(HttpStatusCode.OK); 
      try 
      { 
       if (File.Exists(zipPath)) 
       { 
        var stream = new FileStream(zipPath, FileMode.Open); 
        result.Content = new StreamContent(stream); 
        result.Content.Headers.ContentType = 
         new MediaTypeHeaderValue("application/octet-stream"); 
        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") 
        { 
         FileName = "abc.zip" 
        }; 
       } 
      } 
      catch (Exception ex) 
      { 
       LogError.LogErrorToFile(ex); 
      } 
      return result; 
     } 

    } 
+0

請詳細說明您爲確定這一點所進行的測試。代碼是否在catch塊中記錄錯誤?如果是這樣,那是什麼? –

+0

是的,它表示文件正在被另一個進程訪問,當有一個正在進行的下載請求時。 – Ajay

+2

您可能需要以共享訪問模式打開文件 –

回答

1

它在我提供文件訪問權限時起作用。

public class ZipController : ApiController 
    { 
     [System.Web.Http.AcceptVerbs("GET", "POST")] 
     [System.Web.Http.HttpGet] 
     public HttpResponseMessage DownloadFile() 
     { 
      var zipPath = ConfigurationManager.AppSettings["FilePath"]; 
      var result = new HttpResponseMessage(HttpStatusCode.OK); 
      var stream = new FileStream(zipPath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); 
      try 
      { 
       if (File.Exists(zipPath)) 
       { 

        result.Content = new StreamContent(stream); 
        result.Content.Headers.ContentType = 
         new MediaTypeHeaderValue("application/octet-stream"); 
        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") 
        { 
         FileName = "abc.zip" 

        }; 

       } 
      } 
      catch (Exception ex) 
      { 
       LogError.LogErrorToFile(ex); 
      } 
      return result; 
     } 
    } 
相關問題