Home Core 2.0 MVC - How to link to a dynamic PDF saved on the file system
Reply: 1

Core 2.0 MVC - How to link to a dynamic PDF saved on the file system

user6383418
1#
user6383418 Published in 2018-02-13 20:03:12Z

I have a .NET Core 2.0 MVC project. One of my models has a NotMapped IFormFile field called PDFUpload that takes an upload and saves the file to a place on the file system outside of the root, that path is saved in the PDF field. When users hit a specific URL, the PDF needs to be displayed in the browser or downloaded. My Details.cshtml View currently just shows the path

 @Html.DisplayFor(model => model.PDF)

How do I turn this into an actual link that will serve the file from a specific URL, and not show the path?

Update: Here is the working version

if (System.IO.File.Exists(pdf))
{
    var stream = new FileStream(pdf, FileMode.Open);
    // send the file to the browser
    stream.Position = 0;
    //return File(stream,"application/pdf","filename.pdf") //- will force download
    return new FileStreamResult(stream, "application/pdf");//will display in browser        
}
Becuzz
2#
Becuzz Reply to 2018-02-13 20:19:35Z

You could just make a controller action to serve up the file. You will need some way to identify the file and use that identifier to locate it. Something like this (I used a slug):

public IActionResult GimmeThePdf(string slug)
{
    string filePathToPdf = // look this up in a database given the slug, map the path, etc.
    // open the file for reading
    using (Stream stream = new FileStream(filePathToPdf, FileMode.Open)
    {
        // send the file to the browser
        return File(stream, "application/pdf");
    }
}

Then in your view:

//generate the link, could also do this with tag helpers
@Html.ActionLink("download the pdf", "GimmeThePdf", "YourController", new {slug = Model.PdfSlug});

Which will generate something like this:

<a href="http://yoursite.com/YourController/GimmeThePdf?slug=...">download the pdf</a>
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.365337 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO