ASP.NET Core 2.1 - Download file (push)
[HttpGet]
public async Task<IActionResult> DownloadAsync(int id)
{
var model = _baseRepository.Get<Literature>(id);
var vModel = _mapper.Map<LiteratureViewModel>(model);
if (model == null)
{
return Content(Resources.SharedResource.ErrorDownloadFileFileNotFound);
}
var memory = new MemoryStream();
var fullName = _literatureService.GetFullPath(vModel);
using (var stream = new FileStream(fullName, FileMode.Open))
{
await stream.CopyToAsync(memory);
}
memory.Position = 0;
return File(memory, _literatureService.GetContentType(vModel), vModel.FileName);
}
public string GetContentType(LiteratureViewModel model)
{
var types = GetMimeTypes();
var ext = Path.GetExtension(model.FileName).ToLowerInvariant();
return types[ext];
}
private Dictionary<string, string> GetMimeTypes()
{
return new Dictionary<string, string>
{
{".txt", "text/plain"},
{".pdf", "application/pdf"},
{".doc", "application/vnd.ms-word"},
{".docx", "application/vnd.ms-word"},
{".xls", "application/vnd.ms-excel"},
{".xlsx", "application/vnd.openxmlformatsofficedocument.spreadsheetml.sheet"},
{".png", "image/png"},
{".jpg", "image/jpeg"},
{".jpeg", "image/jpeg"},
{".gif", "image/gif"},
{".csv", "text/csv"}
};
}
No comments:
Post a Comment