欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 名人名企 > ASP.NET Core 下载文件

ASP.NET Core 下载文件

2025/2/24 9:04:01 来源:https://blog.csdn.net/hefeng_aspnet/article/details/144508383  浏览:    关键词: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 下载文件。 

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词