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");
            }
        }
    }
}

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

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

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Part 3 第十二章 单元测试 Unit Testing

概述 第十二章围绕单元测试展开&#xff0c;阐述了单元测试的实践与重要性&#xff0c;通过对比其他测试类型&#xff0c;突出其特点&#xff0c;还介绍了单元测试的最佳实践、避免的反模式以及与测试替身相关的内容&#xff0c;为编写高质量单元测试提供指导。 章节概要 1…

SpringCloud-Eureka初步使用

什么是REST是一组用于规范资源在网络中转移的表现形式软件架构设计风格.简单来说就是客户端和服务器之间的一种交互形式 什么是RESTful,满足了REST风格的接口或者程序,RESTful API是其中的接口,spring中提供了RestTemplate这个类,他强制执行了REST的规范,包括使用HTTP协议的状…

Linux 高级篇 日志管理、定制自己的Linux系统、备份与恢复

一、日志管理 &#xff08;1&#xff09;基本介绍 日志文件是重要的系统信息文件&#xff0c;记录了如用户登录、系统启动、系统安全、邮件及各种服务等相关重要系统事件在安全方面&#xff0c;日志也至关重要&#xff0c;它能记录系统日常发生的各类事情&#xff0c;可用于检…

SpringMVC 请求参数接收

目录 请求 传递单个参数 基本类型参数传递 未传递参数 ?传递参数类型不匹配 传递多个参数 传递对象 后端参数重命名 传递数组 传递集合 传递JSON数据 JSON是什么 JSON的优点 传递JSON对象 获取URL中的参数 文件上传 在浏览器与程序进行交互时&#xff0c;主要…

深度学习之图像回归(一)

前言 图像回归任务主要是理解一个最简单的深度学习相关项目的结构&#xff0c;整体的思路&#xff0c;数据集的处理&#xff0c;模型的训练过程和优化处理。 因为深度学习的项目思路是差不多的&#xff0c;主要的区别是对于数据集的处理阶段&#xff0c;之后模型训练有一些小…

23. AI-大语言模型-DeepSeek简介

文章目录 前言一、DeepSeek是什么1. 简介2. 产品版本1. 类型2. 版本3. 参数规模与模型能力 3. 特征4. 三种访问方式1. 网页端和APP2. DeepSeek API 二、DeepSeek可以做什么1. 应用场景2. 文本生成1. 文本创作2. 摘要与改写3. 结构化生成 3. 自然语言理解与分析1. 语义分析2. 文…

京东cfe滑块 分析

声明: 本文章中所有内容仅供学习交流使用&#xff0c;不用于其他任何目的&#xff0c;抓包内容、敏感网址、数据接口等均已做脱敏处理&#xff0c;严禁用于商业用途和非法用途&#xff0c;否则由此产生的一切后果均与作者无关&#xff01; 逆向分析 headers {"accept&qu…

什么是事务?并发事务引发的问题?什么是MVCC?

文章目录 什么是事务&#xff1f;并发事务引发的问题&#xff1f;什么是MVCC&#xff1f;1.事务的四大特性2.并发事务下产生的问题&#xff1a;脏读、不可重复读、幻读3.如何应对并发事务引发的问题&#xff1f;4.什么是MVCC&#xff1f;5.可见性规则&#xff1f;参考资料 什么…

火语言RPA--Excel插入空行

【组件功能】&#xff1a;在Excel内指定的位置插入空行 配置预览 配置说明 在第n行之前 支持T或# 填写添加插入第n行之前行号。 插入n行 支持T或# 插入多少行。 Sheet页名称 支持T或# Excel表格工作簿名称。 示例 Excel插入空行 描述 在第3行之后插入3行。 配置 输…

【算法基础】--前缀和

前缀和 一、一维前缀和示例模板[寻找数组的中心下标 ](https://leetcode.cn/problems/tvdfij/description/)除自身以外的数组乘积和可被k整除的子数组 一、一维前缀和 前缀和就是快速求出数组某一个连续区间内所有元素的和。 示例模板 已知一个数组arr&#xff0c;求前缀和 …

buuctf-[极客大挑战 2019]Knife题解

一个很简单的web题&#xff0c;进入界面 网页名还加白给的shell&#xff0c;并且给的提示也很明显&#xff0c;给了一个一句话木马再加上菜刀&#xff0c;很怀疑是一个webshell题&#xff0c;那么直接打开蚁剑测试连接拿shell 用提示的一句话木马的密码&#xff0c;测试链接发现…

基于YOLO11深度学习的半导体芯片缺陷检测系统【python源码+Pyqt5界面+数据集+训练代码】

《------往期经典推荐------》 一、AI应用软件开发实战专栏【链接】 项目名称项目名称1.【人脸识别与管理系统开发】2.【车牌识别与自动收费管理系统开发】3.【手势识别系统开发】4.【人脸面部活体检测系统开发】5.【图片风格快速迁移软件开发】6.【人脸表表情识别系统】7.【…

零食店收银pos源码

各位零食店老板&#xff0c;你是否还在为以下问题头疼&#xff1f; 连锁门店越来越多&#xff0c;管理起来力不从心&#xff1f;散装称重商品收银效率低&#xff0c;顾客排队抱怨&#xff1f;线上订单激增&#xff0c;库存混乱&#xff0c;配送跟不上&#xff1f;营销活动花样少…

DeepSeek 冲击(含本地化部署实践)

DeepSeek无疑是春节档最火爆的话题&#xff0c;上线不足一月&#xff0c;其全球累计下载量已达4000万&#xff0c;反超ChatGPT成为全球增长最快的AI应用&#xff0c;并且完全开源。那么究竟DeepSeek有什么魔力&#xff0c;能够让大家趋之若鹜&#xff0c;他又将怎样改变世界AI格…

卷积与动态特征选择:重塑YOLOv8的多尺度目标检测能力

文章目录 1. YOLOv8的网络结构概述2. 添加注意力机制2.1 为什么添加注意力机制&#xff1f;2.2 如何将注意力机制集成到YOLOv8中&#xff1f;2.3 效果分析 3. C2f模块的集成3.1 C2f模块简介3.2 如何在YOLOv8中集成C2f模块&#xff1f;3.3 效果分析 4. 卷积操作的优化4.1 卷积操…

鸿蒙-验证码输入框的几种实现方式-上

文章目录 效果图、优缺点多TextInput多 TextCanvas 绘制 多个 TextInput 拼接放置四个输入框焦点移动输入时向后移动输入完成回调删除时向前移动 防止点击总结 最近在做应用鸿蒙化&#xff0c;说白了就是把原来Android、iOS的代码重新用ArkTS写一遍&#xff0c;我负责基础建设和…

谈谈对线程的认识

面对这样的一个多核CPU时代, 实现并发编程是刚需. 多进程实现并发编程, 效果是特别理想的. 但是, 多线程编程模型有一个明显的缺点, 就是进程太重了, 效率不高. 创建一个进程, 消耗时间比较多. 销毁一个进程, 消耗时间也比较多. 调度一个进程, 消耗时间也比较多. 这里的时…

MySQL的数据类型

4. 数据类型 4.1 数据类型分类4.2 数值类型4.2.1 tinyint类型4.2.2 bit类型4.2.3 小数类型4.2.3.1 float4.2.3.2 decimal 4.3 字符串类型4.3.1 char4.3.2 varchar4.3.3 char和varchar比较 4.4 日期和时间类型enum和set 4.1 数据类型分类 4.2 数值类型 4.2.1 tinyint类型 数值越…

回不去的乌托邦

回不去的乌托邦 坐在电脑面前愣神间已至深夜&#xff0c;依然睡意不起。 相比于带着疲惫入睡&#xff0c;伏案发呆更令人惬意。想起最近在自媒体上看到的一句话“最顶级的享受变成了回不去的乌托邦”。 “这是兄弟们最后一次逛校园了&#xff0c;我拍个照”。我的记忆力总是用在…

分布式与集群,二者区别是什么?

??分布式 分布式系统是由多个独立的计算机节点组成的系统&#xff0c;这些节点通过网络协作完成任务。每个节点都有自己的独立计算能力和存储能力&#xff0c;可以独立运行。分布式系统的目标是提高系统的可靠性、可扩展性和性能。 分布式服务包含的技术和理论 负载均衡&am…