vue下载压缩文件

C#+vue 下载压缩文件

  1. 后台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. 前台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;
       });
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值