Reputation: 3
We are building a Razor Page WebApp that we need our users to be able to download files stored on our server. File path looks like this
//server_name/Databases/PDF_Files/2022-01-01-Invoice.pdf
All the files are on our server. When I put the path in the browser, I am able to view it in the browser.
With the absolute path available, what would be the best way to implement this? A simple code snippet would be much appreciated.
Upvotes: 0
Views: 1032
Reputation: 30120
You can use File.ReadAllBytes
to get a byte array, and then return that as a FileResult
:
public async Task<FileResult> OnGetFile(string filename)
{
var path = @"\\server_name\Databases\PDF_Files";
var file = Path.Combine(path, filename);
return File(await File.ReadAllBytesAsync(file), "application/pdf", filename);
}
The URL for the named handler method above would need to include a query string that has the handler name ("file") and the file name e.g.:
?handler=file&filename=2022-01-01-Invoice.pdf
Obviously, you will need to validate the file name to ensure that it exists and doesn't attempt to access other directories on the server, and you will need to ensure that the account that the web app process runs under has sufficient privileges to access the network resource.
Upvotes: 2