ASP.NET MVC open pdf file in a new window

I have an MVC application. I need to open a pdf file when the user clicks the open button on the page. The path to the file in which pdf is stored is read from the database and is a file in c :. How to open it in my html code? I have this code:

<a href="@Model.CertificatePath" target="_blank" class="button3">Open</a> 

but it does not open my file. What do I need to do? Do I need to indicate somewhere that this is a pdf?

+7
source share
4 answers

You will need to specify the path to the action, which will receive the file name, resolve the full path and then transfer the file to disk from the server to the client. Fortunately, clients on the Internet cannot read files directly from your server's file system (unless ... you assume that @Model.CertificatePath is the file path on the remote user's machine?).

 public ActionResult Download(string fileName) { string path = Path.Combine(@"C:\path\to\files", fileName); return File(path, "application/pdf"); } 

Update

If @Model.CertificatePath is the location on the actual client machine, try:

  <a href="file://@Model.CertificatePath" target="_blank" class="button3">Open</a> 

Please note that some browsers may have security settings that prevent you from opening local files.

+10
source

Try it in your presentation

 @Html.ActionLink("View", "ViewPDF", new { target = "_blank" }) 

Now the link will open in a new window. You can write pdf bytes in the ViewPDF controller method.

+5
source

Unfortunately, you cannot determine where the PDF file will be opened, mainly because you cannot guarantee that the Adobe Acrobat reader plug-in is installed or how it works.

You could theoretically open a new window, and in this new window there is a JavaScript function to open the PDF file, but again you cannot guarantee that it will open in the built-in window without a plug-in, best of all you can hope for a β€œbetter try”.

0
source

You may have a link with fire, for example, a method that below will transfer your selected file to a file download, and not open a PDF file in a browser.

 /// <summary> /// Forces a file to be displayed to the user for download. /// </summary> /// <param name="virtualPath"></param> /// <param name="fileName"></param> public static void ForceDownload(string virtualPath, string fileName) { HttpResponse response = HttpContext.Current.Response; response.Clear(); response.AddHeader("content-disposition", "attachment; filename=" + fileName); response.WriteFile(virtualPath); response.ContentType = ""; response.End(); } 
0
source

All Articles