ASP.NET Core 下载文件

news2025/2/22 6:36:54

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

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2303263.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【信息系统项目管理师-案例真题】2022下半年案例分析答案和详解

更多内容请见: 备考信息系统项目管理师-专栏介绍和目录 文章目录 试题一(24分)【问题1】(6分)【问题2】(10分)【问题3】(8分)试题二(26分)【问题1】(8分)【问题2】(8分)【问题3】(4分)【问题4】(6分)试题三(25分)【问题1】(12分)【问题2】(7分)【问题…

原来DeepSeek还能运用在系统集成-领星对接

在当今数字化转型的浪潮中&#xff0c;企业的信息化建设已成为提升运营效率、优化管理流程的关键。领星ERP与金蝶云星空作为两款在电商和财务管理领域广受欢迎的软件&#xff0c;其数据对接对于跨境电商企业来说尤为重要。本文将结合实际应用场景&#xff0c;深度解析如何通过轻…

在windows下安装windows+Ubuntu16.04双系统(上)

这篇文章的内容主要来源于这篇文章&#xff0c;给文章很详细的介绍了如何从windows下安装windowsubuntu16.04双系统。我刚开始装双系统都是参照这个方法&#xff0c;该作者前后更新了两个版本&#xff0c;在这里对其稍微进行整理一下。 一、准备&#xff1a;&#xff08;这里推…

第37章 合作之路与占坑成功

在春寒料峭的时节&#xff0c;那丝丝寒意宛如一缕缕若有若无的轻烟&#xff0c;在空气中悄然弥漫。锐创所的会议室&#xff0c;宛如一个被岁月尘封的神秘空间&#xff0c;暖黄色的灯光晕染开来&#xff0c;像是为整个房间披上了一层朦胧的薄纱&#xff0c;陈旧却又带着几分温馨…

杰和科技GAM-AI视觉识别管理系统,让AI走进零售营销

在数字化浪潮席卷全球零售业的今天&#xff0c;如何精准触达顾客需求、优化运营效率、提升门店业绩&#xff0c;成为实体商业破局的关键。 GAM-AI视觉识别管理系统 杰和科技智能零售管理系统&#xff1a;GAM-AI视觉识别管理系统&#xff0c;以AI视觉识别大数据分析边缘计算为核…

golang内存泄漏

golang也用了好几年了&#xff0c;趁着有空 整理归纳下&#xff0c;以后忘了好看下 一般认为 Go 10次内存泄漏&#xff0c;8次goroutine泄漏&#xff0c;1次是真正内存泄漏&#xff0c;还有1次是cgo导致的内存泄漏 1:环境 go1.20 win10 2:goroutine泄漏 单个Goroutine占用内存&…

Redis存储⑩Redis的事务_弱化的原子性

目录 1. MySQL和Redis事务的区别 1.1 MySQL的事务 1.2 Redis的事务 2. Redis事务操作 2.1 MULTI multi 2.2 EXEC exec 2.3 DISCARD discard 2.4 WATCH 1. MySQL和Redis事务的区别 1.1 MySQL的事务 MySQL事务复习&#xff1a; MySQL数据库⑨_事务&#xff08;四个属性…

基于Flask的京东商品信息可视化分析系统的设计与实现

【Flask】基于Flask的京东商品信息可视化分析系统的设计与实现&#xff08;完整系统源码开发笔记详细部署教程&#xff09;✅ 目录 一、项目简介二、项目界面展示三、项目视频展示 一、项目简介 系统能够灵活地执行SQL查询&#xff0c;提取出用于分析的关键数据指标。为了将这…

QML ToolButton与DelayButton的使用、详解与自定义样式

QML MenuBarItem与MenuItem的使用、详解与自定义样式 一、介绍1、ToolButton常见用法基础示例设置图标 常用属性texticonenabledshortcutcheckable & checked 信号onClickedonPressed 和 onReleased 样式和外观使用场景 2、DelayButton使用场景核心属性1. delay 核心信号1.…

JSON格式,C语言自己实现,以及直接调用库函数(一)

JSON&#xff08;JavaScript Object Notation&#xff09;是一种轻量级的数据交换格式&#xff0c;易于人阅读和编写&#xff0c;同时也易于机器解析和生成。以下为你提供不同场景下常见的 JSON 格式示例。 1. 简单对象 JSON 对象是由键值对组成&#xff0c;用花括号 {} 包裹&…

学习整理安装php的uuid扩展以及uuid调用方法

学习整理安装php的uuid扩展以及uuid调用方法 1、安装uuid依赖库2、下载并安装3、ini中添加扩展4、re2c版本报错5、uuid调用方法 1、安装uuid依赖库 yum -y install uuid uuid-devel e2fsprogs-devel libuuid-devel2、下载并安装 点我下载uuid安装包 wget http://pecl.php.ne…

Orange 单体架构 - 快速启动

1 后端服务 1.1 基础设施 组件说明版本MySQLMySQL数据库服务5.7/8JavaJava17redis-stackRedis向量数据库最新版本Node安装Node22.11.0 1.2 orange-dependencies-parent 项目Maven依赖版本管理 1.2.1 项目克隆 GitHub git clone https://github.com/hengzq/orange-depende…

Spring Boot 入门 与 无法解析符号 springframework 的解决

Spring Boot 入门的关键步骤 1 创建 Maven 工程 操作目的&#xff1a; 通过 Maven 工程来管理项目依赖&#xff0c;Spring Boot 本身就依赖 Maven 或 Gradle 来简化依赖管理。 操作方法&#xff1a; 打开 IDEA&#xff08;IntelliJ IDEA&#xff09;。点击 New Project&#…

3D模型在线转换工具:轻松实现3DM转OBJ

3D模型在线转换是一款功能强大的在线工具&#xff0c;支持多种3D模型格式的在线预览和互转。无论是工业设计、建筑设计&#xff0c;还是数字艺术领域&#xff0c;这款工具都能满足您的需求。 3DM与OBJ格式简介 3DM格式&#xff1a;3DM是一种广泛应用于三维建模的文件格式&…

网络安全-js安全知识点与XSS常用payloads

简介 JavaScript 是一种轻量级的编程语言&#xff0c;定义了HTML的行为。它与Java的关系类似周杰和周杰伦的关系&#xff08;即没有关系&#xff09;。 用法 HTML 中的脚本必须位于 <script> 与 </script> 标签之间。 脚本可被放置在 HTML 页面的 <body>…

ip属地是电话号码吗怎么改

在数字化时代&#xff0c;IP属地作为网络身份的一部分&#xff0c;对于许多互联网用户来说并不陌生。然而&#xff0c;关于IP属地的具体含义以及如何更改它&#xff0c;却常常让一些用户感到困惑。特别是当提到IP属地与电话号码之间的关系时&#xff0c;更是容易让人产生误解。…

Ubuntu中使用yum命令出现错误提示:Command ‘yum‘ not found

Ubuntu中使用yum命令出现以下错误提示: 解决方法如下 1、使用su或sudo -s命令使普通用户切换为root用户 2、然后检测是否安装了build-essential程序包,输入命令: apt-get install build-essential 3、进度走完后安装yum,输入命令: apt-get install yum 如果成功安装&#xff…

深入理解 JVM 的栈帧结构

&#x1f9d1; 博主简介&#xff1a;CSDN博客专家&#xff0c;历代文学网&#xff08;PC端可以访问&#xff1a;https://literature.sinhy.com/#/literature?__c1000&#xff0c;移动端可微信小程序搜索“历代文学”&#xff09;总架构师&#xff0c;15年工作经验&#xff0c;…

[oeasy]python068_异常处理之后做些什么_try语句的完全体_最终_finally

068_异常处理之后做些什么_finally 异常处理之后做些什么_try语句的完全体_最终_finally 回忆上次内容 我们了解了 try 的细节 except 可以 捕获到异常 但报错比较简单 添加图片注释&#xff0c;不超过 140 字&#xff08;可选&#xff09; 游乐场里面的 报错 更全 更丰富 …

PySide6学习专栏(四):用多线程完成复杂计算任务

如果计程序中要处理一个非常庞大的数据集中的数据&#xff0c;且数据处理计算很复杂&#xff0c;造成数据处理占用大量时间和CPU资源&#xff0c;如果不用多线程&#xff0c;仅在主进程中来处理数据&#xff0c;将会使整个程序卡死&#xff0c;必须采用多线程来处理这些数据是唯…