Create a Service say FileService.
public class FileService
{
private readonly IHostingEnvironment _hostingEnvironment;
constructor(IHostingEnvironment hostingEnvironment)
{
this._hostingEnvironment = hostingEnvironment;
}
}
Add a method to FileService MimeType of the file
private string GetMimeType(string fileName)
{
// Make Sure Microsoft.AspNetCore.StaticFiles Nuget Package is installed
var provider = new FileExtensionContentTypeProvider();
string contentType;
if (!provider.TryGetContentType(fileName, out contentType))
{
contentType = "application/octet-stream";
}
return contentType;
}
Now add a method to download File,
public FileContentResult GetFile(string filename)
{
var filepath = Path.Combine($"{this._environment.WebRootPath}\\path-to-required-folder\\{filename}");
var mimeType = this.GetMimeType(filename);
byte[] fileBytes;
if (File.Exists(filepath))
{
fileBytes = File.ReadAllBytes(filepath);
}
else
{
// Code to handle if file is not present
}
return new FileContentResult(fileBytes, mimeType)
{
FileDownloadName = filename
};
}
Now add controller method and call GetFile method in FileService,
public IActionResult DownloadFile(string filename)
{
// call GetFile Method in service and return
}