2016-10-21 73 views
0

我有這樣的代碼:顯示文件

public void OpenFile(string fileName) 
     { 
      var url = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName); 
      using (var fileStream = new FileStream(url, FileMode.Open)) 
      { 
       byte[] bytes = new byte[fileStream.Length]; 
       int numBytesToRead = (int)fileStream.Length; 
       int numBytesRead = 0; 
       fileStream.Read(bytes,numBytesRead, numBytesToRead);    
      } 
     } 

該代碼工作正常,但我想顯示在瀏覽器文件,我在執行上點擊該方法的名稱文件,參數運行良好,這是我需要在瀏覽器中顯示文件的其他代碼?大多數文件將是.doc和.pdf。我如何在瀏覽器中顯示文檔?

+0

http://stackoverflow.com/questions/3604562/download-file-of-any-type-in​​-asp-net-mvc-using-fileresult – Hackerman

回答

0

您可以從您的操作方法返回FileStreamResult。改變從void方法返回類型ActionResult

public ActionResult OpenFile(string fileName) 
{ 
    var pathToTheFile = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName); 
    var fileStream = new FileStream(pathToTheFile, 
            FileMode.Open, 
            FileAccess.Read 
           ); 
    return new FileStreamResult(fileStream, MimeMapping.GetMimeMapping(fileName));  
}