Skip to content

Instantly share code, notes, and snippets.

@scottsauber
Last active February 19, 2019 05:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottsauber/66836b98b60b7d20f81f8bf5043aa82e to your computer and use it in GitHub Desktop.
Save scottsauber/66836b98b60b7d20f81f8bf5043aa82e to your computer and use it in GitHub Desktop.
[Route("File")]
public class FileController : Controller
{
private readonly IFileService _fileService;
public FileController(IFileService fileService)
{
_fileService = fileService;
}
[HttpPost("Download/{id:guid}")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Download(Guid id)
{
// Retrieve some file from some service
ApplicationFile file = await _fileService.GetFileAsync(id);
var fileProvider = new FileExtensionContentTypeProvider();
// Figures out what the content type should be based on the file name.
if (!fileProvider.TryGetContentType(file.NameWithExtension, out string contentType))
{
throw new ArgumentOutOfRangeException($"Unable to find Content Type for file name {file.NameWithExtension}.");
}
// contentType will be application/pdf for .pdf's, application/vnd.openxmlformats-officedocument.presentationml.presentation for .pptx's, etc.
return File(file.Contents, contentType);
}
}
public class ApplicationFile
{
public string NameWithExtension { get; set; }
public byte[] Contents { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment