vue 下载压缩文件

C#+vue 下载压缩文件

在这里插入图片描述

1 前台VUE代码

安装 blob: npm install blob
安装 axios:npm install axios --save
引用:import axios from ‘axios’
import Blob from ‘blob’;

downloadFile() {
        let url=util.getUrl()+"/api/sys/DownloadFiles"
       this.loading = true;
       axios.get(
        url,//请求的url
        {params:{
                'path':XX //传参
            },
            responseType:'blob'//服务器返回的数据类型
        }).then((res)=>{
         // 处理返回的文件流
         const content = res.data;
         const blob = new Blob([content], { type: "application/zip" });
         const fileName = this.bathCode+".zip";
         if ("download" in document.createElement("a")) {
           // 非IE下载
           const elink = document.createElement("a");
           elink.download = fileName;
           elink.style.display = "none";
           elink.href = URL.createObjectURL(blob);
           document.body.appendChild(elink);
           elink.click();
           URL.revokeObjectURL(elink.href); // 释放URL 对象
           document.body.removeChild(elink);
         } else {
           // IE10+下载
           navigator.msSaveBlob(blob, fileName);
         }
         this.loading = false;
       });

2 后台C#代码

#region 压缩文件
        [Route("api/sys/DownloadFiles")]
        [HttpGet]
        public HttpResponseMessage DownloadFiles(string path)
        {
            try
            {
                string batchCode = path;
                path = FileHelper.LocalPath + "\\" + path;
                if (!Directory.Exists(path))
                {
                    return null;
                }
                var zipFileUrl = FileHelper.LocalPath + batchCode + ".zip";
                if (File.Exists(zipFileUrl))
                {
                    File.Delete(zipFileUrl);
                }

                CreateZipFile(path, zipFileUrl);
                var stream = new FileStream(zipFileUrl, FileMode.Open);
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                response.Content = new StreamContent(stream);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                return response;
            }
            catch (Exception ex)
            {
                return null;
            }
        }


        /// 压缩成zip
        /// </summary>
        /// <param name="folderToZip">d:\</param>
        /// <param name="zipedFile">d:\a.zip</param>
        public static void CreateZipFile(string folderToZip, string zipedFile)
        {
            bool result = false;
            if (!Directory.Exists(folderToZip))
                return;

            ZipOutputStream zipStream = new ZipOutputStream(File.Create(zipedFile));
            zipStream.SetLevel(6);
            //if (!string.IsNullOrEmpty(password)) zipStream.Password = password;

            result = ZipDirectory(folderToZip, zipStream, "");

            zipStream.Finish();
            zipStream.Close();

            return;

        }

        /// <summary>   
        /// 递归压缩文件夹的内部方法   
        /// </summary>   
        /// <param name="folderToZip">要压缩的文件夹路径</param>   
        /// <param name="zipStream">压缩输出流</param>   
        /// <param name="parentFolderName">此文件夹的上级文件夹</param>   
        /// <returns></returns>   
        private static bool ZipDirectory(string folderToZip, ZipOutputStream zipStream, string parentFolderName)
        {
            bool result = true;
            string[] folders, files;
            ZipEntry ent = null;
            FileStream fs = null;

            try
            {
                ent = new ZipEntry(Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/"));
                zipStream.PutNextEntry(ent);
                zipStream.Flush();

                files = Directory.GetFiles(folderToZip);
                foreach (string file in files)
                {
                    fs = File.OpenRead(file);

                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
                    ent = new ZipEntry(Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/" + Path.GetFileName(file)));
                    ent.DateTime = DateTime.Now;
                    ent.Size = fs.Length;

                    fs.Close();
                    zipStream.PutNextEntry(ent);
                    zipStream.Write(buffer, 0, buffer.Length);
                }

            }
            catch
            {
                result = false;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
                if (ent != null)
                {
                    ent = null;
                }
                GC.Collect();
                GC.Collect(1);
            }

            folders = Directory.GetDirectories(folderToZip);
            foreach (string folder in folders)
                if (!ZipDirectory(folder, zipStream, Path.GetFileName(folderToZip)))
                    return false;

            return result;
        }
        #endregion

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
前端可以使用jszip库来进行文件压缩,而Vue框架也提供了与jszip集成的方法。下面是一个使用Vue和jszip压缩文件的简单示例。 首先,需要在Vue项目中安装jszip库。可以使用npm或yarn等包管理工具来安装。 ``` npm install jszip ``` 在Vue组件中引入jszip库并创建一个压缩文件的方法。 ```jsx import JSZip from 'jszip'; export default { data() { return { files: [] // 需要压缩的文件列表 }; }, methods: { async compressFiles() { const zip = new JSZip(); // 遍历文件列表,将每个文件添加到压缩包中 for (const file of this.files) { const content = await this.readFileAsync(file); // 异步读取文件内容 zip.file(file.name, content); // 添加文件到压缩包 } // 生成压缩文件 const zipContent = await zip.generateAsync({ type: 'blob' }); // 下载压缩文件 const link = document.createElement('a'); link.href = URL.createObjectURL(zipContent); link.download = 'compressed.zip'; link.click(); }, readFileAsync(file) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => { resolve(reader.result); }; reader.onerror = reject; reader.readAsArrayBuffer(file); }); } } } ``` 上述代码中,`compressFiles`方法用于处理压缩文件的逻辑。首先创建了一个JSZip的实例。然后遍历文件列表并使用`readFileAsync`方法读取每个文件的内容,并添加到压缩包中。最后通过调用`generateAsync`生成压缩文件的内容,并创建一个下载链接,实现文件的下载。 `readFileAsync`方法使用`FileReader`来异步读取文件内容。通过`readAsArrayBuffer`方法读取文件内容,将读取到的结果作为Promise的返回值。 注意,在以上示例中,假设`this.files`是一个文件列表,表示需要压缩的文件。你可以根据实际情况进行修改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值