How to download PDF file on browser in Asp.net CORE MVC

巧了我就是萌 提交于 2019-12-02 13:18:05

I copied my pdf into the solution and changed the copy to output directory property to copy.

index.cshtml which opens the pdf in a browser tab:

@{
    ViewData["Title"] = "Home Page";
}

<a href="/home/get">Open PDF</a>

index.cshtml which downloads the pdf to file system (include the download attribute on the html anchor tag):

@{
    ViewData["Title"] = "Home Page";
}

<a href="/home/get" download>Download PDF</a>

home controller:

public class HomeController : Controller
{
    public IActionResult Get()
    {
        var stream = new FileStream(@"example.pdf", FileMode.Open);
        return new FileStreamResult(stream, "application/pdf");
    }
}

First,you need to be sure that you have uploaded the file in your project.

Here is a simple demo about how to download pdf on the browser in Asp.Net Core:

1.View:

<a asp-action="GetPdf" asp-controller="Users">Download</a>

2.Controller(be sure that the file have been exsit in wwwroot/file folder):

 [HttpGet]
 public ActionResult GetPdf()
 {
     string filePath = "~/file/test.pdf";
     Response.Headers.Add("Content-Disposition", "inline; filename=test.pdf");
     return File(filePath, "application/pdf");           
 }

3.Startup.cs:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
   //...
   app.UseStaticFiles();
   //...
}

4.Result:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!