• 多个文件合并压缩导出


    话不多说,直接上代码

    public async Task<FileDto> Export_Zip(Export_ZipInput input)
    {
    var userid = 1;
    var userName = "张三";
    var file_zip = new FileDto(DateTime.Now.ToString("yyyyMMddHHmmssfff") + "-费用表" + ".zip", MimeTypeNames.ApplicationZip);//最后压缩的文件

    var contents= _companyExpenseItemRepository.GetAll();

    var streams = new Dictionary<string, Stream>();
    var md5StreamList = new List<string>();
    Stream streamWriter = null;
    int i = 0;
    foreach (var id in input.Ids)
    {
    i++;

    var file = ExportCompanyExpenseDetails_Demo(id, 0, userName); //单个费用表的构造,此处不重复说明
    //压缩
    if (!streams.Any(p => p.Key == i.ToString() + "_" + file.FileName)) //为了防止名称重复,我给他加了一个编号
    {
    var filePath = Path.Combine(AppFolders.TempFileDownloadFolder, file.FileToken);
    var newStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
    var md5Stream = MD5Stream(newStream);
    newStream.Close();

    if (!md5StreamList.Exists(p => p == md5Stream))
    {
    streamWriter = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
    streams.Add(i.ToString() + "_" + file.FileName, streamWriter);

    md5StreamList.Add(md5Stream);
    }
    }
    }

    if (!streams.Any())
    {
    throw new UserFriendlyException("没有数据!");
    }

    MemoryStream ms = Compress.PackageManyZip(streams);
    byte[] bytes = new byte[(int)ms.Length];
    ms.Read(bytes, 0, bytes.Length);
    ms.Close();
    //创建一个文件流
    FileStream fs = new FileStream(Path.Combine(AppFolders.TempFileDownloadFolder, file_zip.FileToken), FileMode.Create);
    //将byte数组写入文件中
    fs.Write(bytes, 0, bytes.Length);
    //所有流类型都要关闭流,否则会出现内存泄露问题
    foreach (var steam in streams)
    {
    steam.Value.Close();
    }
    fs.Close();
    }
    return file_zip;
    }

  • 相关阅读:
    apache反向代理和负载均衡
    maven学习3,如何创建一个web项目
    初识maven及其安装步骤!!
    初识Eclipse!!
    登录页面!!!
    面向对象的三大要素
    【转载】fatal error C1010: unexpected end of file while looking for precompiled header directive
    C++ 读取XML 和TXT
    python +Libsvm 配置
    C++ 引用 和 指针 心得
  • 原文地址:https://www.cnblogs.com/luoxiaoxiao102/p/14455580.html
Copyright © 2020-2023  润新知