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

ASP.NET Core 下载文件

本文使用 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 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");
            }
        }
    }
}

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

相关文章:

  • 如何基于transformers库通过训练Qwen/DeepSeek模型的传统分类能力实现文本分类任务
  • cs106x-lecture13(Autumn 2017)-SPL实现
  • 【Linux网络编程】IP协议格式,解包步骤
  • 模拟实现Java中的计时器
  • C++17中的std::scoped_lock:简化多锁管理的利器
  • android 网络防护 手机网络安全怎么防
  • 【算法】----多重背包问题I,II(动态规划)
  • Redis-线程模型
  • VMware下ubuntu-24.04.1系统的下载与安装(保姆级)
  • 【Spring详解四】自定义标签的解析
  • Zabbix——自定义监控项脚本分享
  • Grafana 快速部署监控视图指南
  • leetcode day19 844+977
  • java项目之风顺农场供销一体系统的设计与实现(源码+文档)
  • Html5学习教程,从入门到精通,HTML5 简介语法知识点及案例代码(1)
  • 如何通过 Homebrew 安装 Qt 并配置环境变量
  • 【Linux网络】认识协议(TCP/UDP)、Mac/IP地址和端口号、网络字节序、socket套接字
  • 一文讲解Redis中的基本数据类型
  • PcVue : 点亮马来西亚砂拉越偏远村庄
  • Linux阿里云服务器安装RocketMQ教程
  • 创建简易个人网站/推广普通话的意义论文
  • bc网站搭建网站开发/长沙优化网站厂家
  • 中国建设部网站-玻璃幕墙/网络整合营销案例
  • 阳江网络公司/郑州网站优化
  • 信用门户网站建设观摩/在线优化seo
  • 17网站一起做网店打不开/建站教程