加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

下载ASP.NET MVC C#中字节数组列表中包含的多个文件

发布时间:2020-12-15 19:53:08 所属栏目:asp.Net 来源:网络整理
导读:我正在开发一个ASP.NET MVC 5应用程序,我写了一个代码,允许我下载存储在SQL Server数据库中的文件作为varbinary,我可以用这个下载单个文件: public JsonResult PrepareSingleFile(int [] IdArray){ ImageContext _contexte = new ImageContext(); var respo
我正在开发一个ASP.NET MVC 5应用程序,我写了一个代码,允许我下载存储在SQL Server数据库中的文件作为varbinary,我可以用这个下载单个文件:
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文件下载,那么我该怎么做呢?

我试过这个:

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

但是当数据是List< byte []>时它不起作用.

解决方法

您可以使用.NET framework 4.5中提供的 ZipArchive类来实现.
您可以在控制器中添加一个接受List< byte []>的方法.参数然后将每个byte []转换为一个内存流并将其放入像这样的zip文件中,
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,file.Length);
                    }
                }
            }

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读