Returning a file to View/Download in ASP.NET MVC

前端 未结 9 1597
刺人心
刺人心 2020-11-21 22:41

I\'m encountering a problem sending files stored in a database back to the user in ASP.NET MVC. What I want is a view listing two links, one to view the file and let the mim

9条回答
  •  [愿得一人]
    2020-11-21 22:48

    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"},
                ...
            };
        }
    }
    

提交回复
热议问题