当前位置: 首页 > article >正文

ASP.NET Core 下载文件

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

当返回文件时,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 wwwroot 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.NET Core 应用程序中从 URL/URI 下载文件。
如果使用.NET Framework,请参阅如何使用 .NET Framework 下载文件。 

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


http://www.kler.cn/a/468309.html

相关文章:

  • 【全栈】SprintBoot+vue3迷你商城(1)
  • http源码分析
  • Visual Studio 2022+Qt6.5.3安装教程+环境配置+创建Qt项目+乱码插件+运行很完美(16岁孩子也能看懂)
  • 计算机的错误计算(二百零一)
  • 计算机网络--路由器问题
  • [python3]Excel解析库-xlutils
  • AIA - APLIC之三(附APLIC处理流程图)
  • [读书日志]8051软核处理器设计实战(基于FPGA)第四篇:verilog语法特性
  • 任务执行模式全解析:并发、并行、串行与同步、异步的对比
  • Sentinel-5P遥感数据下载及预处理教程【20250105】
  • 每天学一点强化学习(二)
  • 树莓派 Pico RP2040 多核心运行模式 多核编程
  • 圆周率π为何是无穷无尽的
  • Rust中的Option枚举快速入门
  • LookingGlass使用
  • [react+ts] useRef获取自定义组件dom或方法声明
  • Windows 11 上配置VSCode 使用 Git 和 SSH 完整步骤
  • Go语言的 的反射(Reflection)核心知识
  • springboot远程链接Hadoop
  • launch.json传递True值