下载ASP.NET MVC C#字节数组列表中包含的多个文件 [英] Download multiple files contained in a list of byte array in ASP.NET MVC C#

查看:61
本文介绍了下载ASP.NET MVC C#字节数组列表中包含的多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发ASP.NET MVC 5应用程序,并且编写了一个代码,该代码允许我以varbinary的形式下载存储在SQL Server数据库中的文件,我可以通过以下方式下载单个文件:

I'm developing an ASP.NET MVC 5 application, and I wrote a code that allows me to download files stored in a SQL Server database as varbinary, I'm able to download a single file with this:

public JsonResult PrepareSingleFile(int [] IdArray)
{
    ImageContext _contexte = new ImageContext();
    var response =_contexte.contents.Find(IdArray.FirstOrDefault());
    //byte[] FileData = 
    Encoding.UTF8.GetBytes(response.image.ToString());
    byte[] FileData = response.image;
    Session["data"] = FileData;
    Session["filename"] = response.FileName;

    return Json(response.FileName);
}

public FileResult DownloadSingleFile()
{
    var fname = Session["filename"];
    var data = (byte[]) Session["data"];
    //return File(data,"application/pdf");
    return File(data,System.Net.Mime.MediaTypeNames.Application.Pdf, fname.ToString()+".pdf");
}

但是现在我想下载多个文件,因此我将每个文件的数据作为字节数组并将这些字节数组放入List<byte[]>中,并且我想将这些文件下载为zip文件.我能做到吗?

But now I want to download multiple files, so I'm getting the data of each file as a byte array and putting those byte arrays inside a List<byte[]> and I want to download those files as a zip file, so how can I do that?

我尝试过:

File(data,"the Mime Type", "file name.extension")

但是当dataList<byte[]>时不起作用.

推荐答案

您可以使用

You can do that using ZipArchive class available in .NET framework 4.5. You may add a method in your controller that accepts a List<byte[]> parameter and then converts each byte[] to a memory stream and puts it in a zip file like this one,

 public FileResult DownloadMultipleFiles(List<byte[]> byteArrayList)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            using (var archive = new ZipArchive(ms, ZipArchiveMode.Create, true))
            {
                foreach(var file in byteArrayList)
                {
                    var entry = archive.CreateEntry(file.fileName +".pdf", CompressionLevel.Fastest);
                    using (var zipStream = entry.Open()) 
                    {
                        zipStream.Write(file, 0, file.Length);
                    }
                }
            }

            return File(ms.ToArray(), "application/zip", "Archive.zip");
        }
    }

这篇关于下载ASP.NET MVC C#字节数组列表中包含的多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆