How to displaying a PDF Document in outside folder

2019-08-23 16:25发布

问题:

Currently i'm working with document management system project technology is ASP.Net MVC 3 . i want to display pdf document that is located in folder in my hard drive(C:,D: E: ect). i tried to <embed> tag. but it didn't work. it worked for files inside my project. Also i don't need to download that pdf and read. i need to dispaly it somewhere in my view.

i saw this code segment. but i don't know how to use this..

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);
}

Can someone help me to solve this problem. Thank You

回答1:

The code you have shown represents a controller action that serves files from the App_Code folder. Serving files from arbitrary locations on the hard drive would be a huge security vulnerability. So I would recommend you sticking with this approach. But there are still flaws in this code. A malicious user could still display arbitrary files on your hard drive by using a specially crafted url. This could be fixed with the following action:

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);
}

and now you could use the embed tag to link to this controller action:

<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>

or an iframe if you prefer:

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


回答2:

You may ise the File method of Controller class. This will return the PDF to browser.

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

Assuming SomeMethodToGetFullPathFromFileName is a method which returns the full path to the PDF file

You may use Server.MapPath method to get the full (physical) path to the file.

If you want to view this in the browser, you can access it like

yoursitename/someControllername/getfile?fileName=somepdffilenamehere