How to download a file in ASP.NET Core

后端 未结 9 1994
离开以前
离开以前 2020-12-02 13:14

In MVC, we have used following code to download a file. In ASP.NET core, how to achieve this?

HttpResponse response = HttpContext.Current.Response;                   


        
9条回答
  •  感动是毒
    2020-12-02 13:28

    Action method needs to return FileResult with either a stream, byte[], or virtual path of the file. You will also need to know the content-type of the file being downloaded. Here is a sample (quick/dirty) utility method. Sample video link How to download files using asp.net core

    [Route("api/[controller]")]
    public class DownloadController : Controller
    {
        [HttpGet]
        public async Task Download()
        {
            var path = @"C:\Vetrivel\winforms.png";
            var memory = new MemoryStream();
            using (var stream = new FileStream(path, FileMode.Open))
            {
                await stream.CopyToAsync(memory);
            }
            memory.Position = 0;
            var ext = Path.GetExtension(path).ToLowerInvariant();
            return File(memory, GetMimeTypes()[ext], Path.GetFileName(path));
        }
    
        private Dictionary GetMimeTypes()
        {
            return new Dictionary
            {
                {".txt", "text/plain"},
                {".pdf", "application/pdf"},
                {".doc", "application/vnd.ms-word"},
                {".docx", "application/vnd.ms-word"},
                {".png", "image/png"},
                {".jpg", "image/jpeg"},
                ...
            };
        }
    }
    

提交回复
热议问题