Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying PDF ASP.Net MVC

Tags:

asp.net-mvc

I have a file on my desktop for test. I am trying to display it in a view that looks like this:

@{
    ViewBag.Title = "ShowFile";
}

<h2>ShowFile</h2>

The code I am using for the controller is:

   [HttpGet]
        public ActionResult ShowFile(string path)
        {
            path = @"C:\Documents and Settings\nickla\Desktop\nlamarca_06_15.pdf";

            return File(path, "application/pdf", "nlamarca_06_15.pdf");
        }

When I run this code the view displays "undefined" any ideas on what could be wrong here?

like image 389
Nick LaMarca Avatar asked Jan 17 '23 02:01

Nick LaMarca


2 Answers

You don't seem to have specified the filename in your path:

public ActionResult ShowFile(string filename)
{
    var path = @"C:\Documents and Settings\nickla\Desktop";
    var file = Path.Combine(path, filename);
    file = Path.GetFullPath(file);
    if (!file.StartsWith(path))
    {
        // someone tried to be smart and sent 
        // ?filename=..\..\creditcard.pdf as parameter
        throw new HttpException(403, "Forbidden");
    }
    return File(file, "application/pdf");
}
like image 185
Darin Dimitrov Avatar answered Jan 25 '23 14:01

Darin Dimitrov


You are missing the file name in the path. your path only up to the directory. Give the full PDF file name.

public ActionResult ShowFile(string path)
{
   //not sure why you overwrote although you have a parameter to pass the path

    path = @"C:\Documents and Settings\nickla\Desktop\nlamarca_06_15.pdf";
    return File(path, "application/pdf", "nlamarca_06_15.pdf");
}

Assuming the PDF file name you have in that particular directory is nlamarca_06_15.pdf

like image 32
Shyju Avatar answered Jan 25 '23 15:01

Shyju