2012-09-10 68 views
0

目前我正在使用文檔管理系統項目技術是ASP.Net MVC 3。我想顯示位於我硬盤驅動器(C:,D:E:ect)文件夾中的pdf文檔。我試圖<embed>標籤。但它不起作用。它適用於我的項目中的文件。我也不需要下載該pdf並閱讀。我需要在我看來的地方展示它。如何在瀏覽器的外部文件夾中顯示PDF文檔

我看到了這段代碼。但我不知道如何使用..

public FileResult GetFile(string fileName) 
{ 
    Response.AppendHeader("Content-Disposition", "inline; filename=" + fileName + ";"); 
    string path = AppDomain.CurrentDomain.BaseDirectory + "App_Data/";    
    return File(path + fileName, System.Net.Mime.MediaTypeNames.Application.Pdf, fileName); 
} 

有人可以幫我解決這個問題。 謝謝

回答

0

您可能是Controller類的File方法。這將把PDF返回給瀏覽器。

public ActionResult GetFile(string fileName) 
{ 
    string fullPathToFile=SomeMethodToGetFullPathFromFileName(fileName); 
    return File(fullPathToFile,"application/pdf","someFriendlyName.pdf") 
} 

假設SomeMethodToGetFullPathFromFileName是返回到PDF文件

的完整路徑,您可以使用Server.MapPath方法來獲得完整的(物理)文件路徑的方法。

如果你想在瀏覽器中查看此,您可以訪問它喜歡

yoursitename/someControllername/getfile?fileName=somepdffilenamehere 
+0

文件已下載。我需要在我的「視圖」中顯示該pdf。 – Krishan

+0

下載到哪裏?怎麼樣 ? – Shyju

0

你已經顯示的代碼表示,供應從App_Code文件夾中的文件的控制器操作。從硬盤上的任意位置提供文件將是一個巨大的安全漏洞。所以我建議你堅持這種做法。但是這個代碼仍然存在缺陷。惡意用戶仍然可以使用特製的url在硬盤上顯示任意文件。這可以被固定了以下行動:

public ActionResult GetFile(string file) 
{ 
    var appData = Server.MapPath("~/App_Data"); 
    var path = Path.Combine(appData, file); 
    path = Path.GetFullPath(path); 
    if (!path.StartsWith(appData)) 
    { 
     // Ensure that we are serving file only inside the App_Data folder 
     // and block requests outside like "../web.config" 
     throw new HttpException(403, "Forbidden"); 
    } 

    if (!System.IO.File.Exists(path)) 
    { 
     return HttpNotFound(); 
    } 

    return File(path, MediaTypeNames.Application.Pdf); 
} 

,現在你可以使用embed標籤鏈接到這個控制器動作:

<object data="@Url.Action("GetFile", "SomeController", new { file = "test.pdf" })" type="application/pdf" width="300" height="200"> 
    alt : @Html.ActionLink("test.pdf", "SomeController", "Home", new { file = "test.pdf" }) 
</object> 

iframe如果你喜歡:

<iframe src="@Url.Action("GetFile", "SomeController", new { file = "foo.pdf" })" style="width:718px; height:700px;" frameborder="0"></iframe> 
相關問題