主页 > IT业界  > 

ASP.NETCore下载文件

ASP.NETCore下载文件

本文使用 ASP .NET Core,适用于 .NET Core 3.1、.NET 5、.NET 6和.NET 8。

另请参阅: 如何在将文件发送到浏览器后自动删除该文件。 如何将文件从浏览器上传到服务器。 如何在 ASP.NET Core 应用程序中从 URL/URI 下载文件。 如果使用.NET Framework,请参阅如何使用 .NET Framework 下载文件。

当返回文件时,FileResult方法返回类型可以像 一样使用IActionResult。

下载文件最快捷、最简单的方法是使用虚拟路径指定文件名。MIME-Type/Content-Type 也是必需的。有效值不限于“image/jpeg”、“image/gif”、“image/png”、“text/plain”、“application/x-zip-compressed”和“application/json”。

System.Net.Mime.MediaTypeNames.Application.Json

using Microsoft.AspNetCore.Mvc;

namespace Website.Controllers {     public class HomeController : Controller     {         public IActionResult Index()         {             return View();         }         public FileResult DownloadFile() // can also be IActionResult         {             // this file is in the root folder             return File("/test.txt", "text/plain");         }     } }

下载的另一种方法是附加内容处置标头。别担心,ASP.NET Core 使用 MVC 5 使它比过去更简单。

using Microsoft.AspNetCore.Mvc;

namespace Website.Controllers {     public class HomeController : Controller     {         public IActionResult Index()         {             return View();         }         public FileResult DownloadFile() // can also be IActionResult         {             // this will append the content-disposition header and download the file to the computer as "downloaded_file.txt"             return File("/test.txt", "text/plain", "downloaded_file.txt");         }     } }

另一种方法是使用Stream。此示例中的代码量大大增加,但其功能与示例 1 相同。

using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using System.IO;

namespace Website.Controllers {     public class HomeController : Controller     {         private IWebHostEnvironment env { get; }

        public HomeController(IWebHostEnvironment env) => this.env = env;

        public IActionResult Index()         {             return View();         }         public FileResult DownloadFile() // can also be IActionResult         {             string file = System.IO.Path.Combine(env.WebRootPath, "test.txt");             return File(new FileStream(file, FileMode.Open), "text/plain"); // could have specified the downloaded file name again here         }     } }

另一种方法是从文件中读取字节,但这需要更多的内存并且在处理文件时效率不高。

using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc;

namespace Website.Controllers {     public class HomeController : Controller     {         private IWebHostEnvironment env { get; }

        public HomeController(IWebHostEnvironment env) => this.env = env;

        public IActionResult Index()         {             return View();         }         public FileResult DownloadFile() // can also be IActionResult         {             string file = System.IO.Path.Combine(env.WebRootPath, "test.txt");             byte[] data = System.IO.File.ReadAllBytes(file);             return File(data, "text/plain"); // could have specified the downloaded file name again here         }     } }

以下是下载 zip 文件的示例。请注意,FileStream fs已关闭,zip.Close();因此必须重新打开。

using ICSharpCode.SharpZipLib.Zip; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc;

namespace Website.Controllers {     public class HomeController : Controller     {         private IWebHostEnvironment env { get; }

        public HomeController(IWebHostEnvironment env) => this.env = env;

        public IActionResult Index()         {             return View();         }         public FileResult DownloadFile() // can also be IActionResult         {             string file = System.IO.Path.Combine(env.WebRootPath, "temp.zip"); // in production, would probably want to use a GUID as the file name so that it is unique             System.IO.FileStream fs = System.IO.File.Create(file);             using (ZipOutputStream zip = new ZipOutputStream(fs))             {                 byte[] data;                 ZipEntry entry;                 entry = new ZipEntry("downloaded_file.txt");                 entry.DateTime = System.DateTime.Now;                 zip.PutNextEntry(entry);                 data = System.IO.File.ReadAllBytes(System.IO.Path.Combine(env.WebRootPath, "test.txt"));                 zip.Write(data, 0, data.Length);                 zip.Finish();                 zip.Close();                 fs.Dispose(); // must dispose of it                 fs = System.IO.File.OpenRead(file); // must re-open the zip file                 data = new byte[fs.Length];                 fs.Read(data, 0, data.Length);                 fs.Close();                 System.IO.File.Delete(file);                 return File(data, "application/x-zip-compressed", "downloaded_file.zip"); // recommend specifying the download file name for zips             }         }     } }

这也同样有效(用于System.Net.Mime.MediaTypeNamesContent-Type):

using ICSharpCode.SharpZipLib.Zip; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc;

namespace Website.Controllers {     public class HomeController : Controller     {         private IWebHostEnvironment env { get; }

        public HomeController(IWebHostEnvironment env) => this.env = env;

        public IActionResult Index()         {             return View();         }         public FileResult DownloadFile() // can also be IActionResult         {             string file = System.IO.Path.Combine(env.WebRootPath, "temp.zip"); // in production, would probably want to use a GUID as the file name so that it is unique             System.IO.FileStream fs = System.IO.File.Create(file);             using (ZipOutputStream zip = new ZipOutputStream(fs))             {                 byte[] data;                 ZipEntry entry;                 entry = new ZipEntry("downloaded_file.txt");                 entry.DateTime = System.DateTime.Now;                 zip.PutNextEntry(entry);                 data = System.IO.File.ReadAllBytes(System.IO.Path.Combine(env.WebRootPath, "test.txt"));                 zip.Write(data, 0, data.Length);                 zip.Finish();                 zip.Close();                 fs.Dispose(); // must dispose of it                 fs = System.IO.File.OpenRead(file); // must re-open the zip file                 data = new byte[fs.Length];                 fs.Read(data, 0, data.Length);                 fs.Close();                 System.IO.File.Delete(file);                 return File(data, System.Net.Mime.MediaTypeNames.Application.Zip, "downloaded_file.zip"); // ZIP             }         }     } }

就像这样:

using ICSharpCode.SharpZipLib.Zip; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc;

namespace Website.Controllers {     public class HomeController : Controller     {         private IWebHostEnvironment env { get; }

        public HomeController(IWebHostEnvironment env) => this.env = env;

        public IActionResult Index()         {             return View();         }         public FileResult DownloadFile() // can also be IActionResult         {             string file = System.IO.Path.Combine(env.WebRootPath, "temp.zip"); // in production, would probably want to use a GUID as the file name so that it is unique             System.IO.FileStream fs = System.IO.File.Create(file);             using (ZipOutputStream zip = new ZipOutputStream(fs))             {                 byte[] data;                 ZipEntry entry;                 entry = new ZipEntry("downloaded_file.txt");                 entry.DateTime = System.DateTime.Now;                 zip.PutNextEntry(entry);                 data = System.IO.File.ReadAllBytes(System.IO.Path.Combine(env.WebRootPath, "test.txt"));                 zip.Write(data, 0, data.Length);                 zip.Finish();                 zip.Close();                 fs.Dispose(); // must dispose of it                 fs = System.IO.File.OpenRead(file); // must re-open the zip file                 data = new byte[fs.Length];                 fs.Read(data, 0, data.Length);                 fs.Close();                 System.IO.File.Delete(file);                 return File(data, System.Net.Mime.MediaTypeNames.Application.Octet, "downloaded_file.zip"); // OCTET             }         }     } }

或者使用System.IO.Compression创建zip 档案:

using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using System.IO.Compression; using System.Text;

namespace Website.Controllers {     public class ZipController : Controller     {         public ZipController() {}

        public IActionResult Index()         {             return View();         }         public async Task<FileResult> DownloadFile() // can also be IActionResult         {             using (MemoryStream zipoutput = new MemoryStream())             {                 using (ZipArchive archive = new ZipArchive(zipoutput, ZipArchiveMode.Create, false))                 {                     ZipArchiveEntry entry = archive.CreateEntry("test.txt", CompressionLevel.Optimal);                     using (var entryStream = entry.Open())                     {                         byte[] buffer = Encoding.UTF8.GetBytes("This is a test!!!");                         using (var ms = new MemoryStream(buffer))                         {                             await ms.CopyToAsync(entryStream);                         }                     }                     entry = archive.CreateEntry("test2.txt", CompressionLevel.Optimal);                     using (var entryStream = entry.Open())                     {                         byte[] buffer = Encoding.UTF8.GetBytes("This is another test!!!");                         using (var ms = new MemoryStream(buffer))                         {                             await ms.CopyToAsync(entryStream);                         }                     }                 }                 return File(zipoutput.ToArray(), "application/x-zip-compressed", "test-txt-files.zip");             }         }     } }

或者从中读取简单字节MemoryStream:

using Microsoft.AspNetCore.Mvc;

namespace Website.Controllers {     public class HomeController : Controller     {         public IActionResult Index()         {             return View();         }         public FileResult DownloadFile() // can also be IActionResult         {             using (var ms = new System.IO.MemoryStream())             {                 ms.WriteByte((byte)'a');                 ms.WriteByte((byte)'b');                 ms.WriteByte((byte)'c');                 byte[] data = ms.ToArray();                 return File(data, "text/plain", "downloaded_file.txt");             }         }     } }

如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。 

标签:

ASP.NETCore下载文件由讯客互联IT业界栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“ASP.NETCore下载文件