What I would like to do is have a stored file path in a database that appears as a hyperlink and if clicked, it starts a download. In the future I would want to store multiple different file paths in database, and show them in a gridview.
I tried something like this – in the database, Downloads
table, path:
<a href="~\wwwroot\Contents\sample.pdf" target="_blank">Download</a>
but this doesn’t work as it cannot find file location.
Is it even possible doing it like this?
First, you don’t need to include the wwwroot
in the href, using href="/Contents/sample.pdf"
should work for you. remember, ASP.NET Core uses wwwroot folder by default when resolving static files (CSS, JS, Images etc), so using ~\wwwroot\Contents\sample.pdf essentially means looking for wwwroot sub folder inside wwwroot foler. Let’s say the project is located at D:\dev\xyx, .net core will be looking for d:\dev\xyx\wwwroot\wwwroot\Contents\sample.pdf which is not correct (pay attention to the double wwwroot). the correct path should be d:\dev\xyx\wwwroot\Contents\sample.pdf
Second, you should never store the absolute file paths in the database, this is not a good practice. Save paths relative to your download folder in the database and then resolve them on the fly (dynamically) when rendering a tag.