vue+springboot压缩多个文件、压缩包下载、单文件下载

1、vue代码

 // 下载文件
 downloadF(rowId,rowName){
   var id = rowId==null ? this.ids : rowId;
   console.log(id.length);
   var name = rowName==null? this.names :rowName;
   if (id.length > 1) name = "downLoad.zip";

   downLoadFile(id).then(function(response) {
       //const blob = response;
       const blob=new Blob([response]);
       var size = blob.size;
       if (size == 0){
           Vue.prototype.$message({
               message :"没有对应文件!",
               type: 'warning'
           });
       }else{
           if ('download' in document.createElement('a')) {
               // 非IE下载
               const elink = document.createElement('a');
               elink.download = name;
               elink.style.display = 'none';
               elink.href = URL.createObjectURL(blob);
               document.body.appendChild(elink);
               elink.click();
               // 释放URL对象
               URL.revokeObjectURL(elink.href);
               document.body.removeChild(elink);
           } else {
               navigator.msSaveBlob(blob, name)
           }
       }
   }, function(err) {
   });
 }

2、接口

//文件下载
export function downLoadFile(fileIds) {
  return request({
    url:'/eos/upload/download/fileId/'+fileIds,
    method:'get',
    responseType:'blob'
  })
}

3、controller层,分为单文件下载和多文件下载

import java.io.*;
import java.math.BigDecimal;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ZipUtil;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.eos.domain.upload.EosFileUpload;
import com.ruoyi.eos.service.upload.IEosFileUploadService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;

	
    private String FILE_ROOT_PATH = "D:/zipFile";
    private static String ZIP_PATH = "D:/test.zip";
    private static int NUM = 1;
  /**
   * 下载文件
   * @param fileIds 文件id
   * @param request
   * @return
   * @throws Exception
   */
  @GetMapping("/download/fileId/{fileIds}")
  public ResponseEntity<ByteArrayResource> downLoadFile(@PathVariable("fileIds")ArrayList<Integer> fileIds ,
      HttpServletRequest request)
      throws Exception {

      int size = fileIds.size();
      NUM = 1;

      if (size== 0 || fileIds == null){
          throw new Exception("下载文件id数组为空!");
      }

      if(size == 1){
          //单文件下载
          return downLoadOne(fileIds.get(0));
      }else {
          //多文件下载,打包成ZIP
          FileUtil.del(new File(FILE_ROOT_PATH));
          for (int j = 0; j<size ; j++){
              EosFileUpload eosFileUpload = eosFileUploadService.selectEosFileUploadByFileId((long)fileIds.get(j));
              String fileName = eosFileUpload.getFileName();
              String saveName = eosFileUpload.getFileNameSaved();
              String filePath = lastThirdCharString(eosFileUpload.getFilePath());
              String downPath =RuoYiConfig.getUploadPath()+File.separator+filePath+File.separator+saveName;
              System.out.println(downPath);
              Long downloadCount= eosFileUpload.getDownloadCount();
              //设置新的下载日期和下载次数
              eosFileUpload.setDownloadDate(new Date());
              eosFileUpload.setDownloadCount(downloadCount+1);
              //获取对应文件字节数组
              byte[] data = Files.readAllBytes(Paths.get(downPath));
              //先把文件写入文件夹,代码看下图
              writeBytes(data,FILE_ROOT_PATH,fileName);
              //修改一些字段
              eosFileUploadService.updateEosFileUpload(eosFileUpload);

          }
          //压缩已经写入文件的文件夹,并获得压缩包路径,代码看下图
          String zipPath = downZIP(FILE_ROOT_PATH);
          //下载文件
          byte[] data = Files.readAllBytes(Paths.get(zipPath));
          ByteArrayResource resource = new ByteArrayResource(data);
         
         //删除临时文件
         FileUtil.del(new File(FILE_ROOT_PATH));
         FileUtil.del(new File(ZIP_PATH));
          
          return ResponseEntity.ok()
              .header(HttpHeaders.CONTENT_DISPOSITION)
              .contentType(MediaType.APPLICATION_OCTET_STREAM)
              .contentLength(data.length)
              .body(resource);
      }

  }

4、一些需要的方法

   /**
    * 写数据到文件中
    *
    * @param data 数据
    * @param uploadDir 目标文件
    * @return 目标文件
    * @throws IOException IO异常
    */
   public static void writeBytes(byte[] data, String uploadDir,String fileName) throws IOException
   {
       FileOutputStream fos = null;
       String pathName = "";
       String fileSuffix = getSuffix(fileName);
       try
       {
           pathName = DateUtils.datePath() + "/" +fileName;
           File file = getAbsoluteFile(uploadDir, pathName);
           fos = new FileOutputStream(file);
           fos.write(data);
       }
       finally
       {
           IOUtils.close(fos);
       }
       //return FileUploadUtils.getPathFileName(uploadDir, pathName);
   }
   /**
    * 把多个文件压缩
    * @param s 文件路径,可以是文件、文件夹
    * @return 压缩包路径
    */
   public static String downZIP(String s){
   		//ZipUtil.zip()是一个工具类,具体看图一的import
       File file =  ZipUtil.zip(s,ZIP_PATH);
       return file.getAbsolutePath();
   }
  /**
   * 获取文件后缀名
   * @param fileName
   * @return
   */
  public static String getSuffix(String fileName){
      StringBuffer stringBuffer = new StringBuffer(fileName);
      int index = stringBuffer.indexOf(".");
      return stringBuffer.substring(index,stringBuffer.length());
  }

  /**
   * 获取文件名
   * @param fileName
   * @return
   */
  public static String getPrefix(String fileName){
      StringBuffer stringBuffer = new StringBuffer(fileName);
      int index = stringBuffer.indexOf(".");
      return stringBuffer.substring(0,index);
  }

//判断文件是否存在,如果存在,就再文件名后添加(1)、(2)等修饰。
  public static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException
  {
      File desc = new File(uploadDir + File.separator + fileName);

      if (!desc.exists())
      {
          if (!desc.getParentFile().exists())
          {
              desc.getParentFile().mkdirs();
          }
      }else {
          desc = new File(uploadDir + File.separator + getPrefix(fileName)+"("+NUM+")"+getSuffix(fileName));
          NUM++;
      }
      return desc;
  }

5、单文件下载

   /**
    * 单个文件下载
    * @param fileId
    * @return
    * @throws Exception
    */
   public ResponseEntity<ByteArrayResource> downLoadOne(int fileId) throws Exception{
       EosFileUpload eosFileUpload = eosFileUploadService.selectEosFileUploadByFileId((long)fileId);
       String fileName = eosFileUpload.getFileName();
       String saveName = eosFileUpload.getFileNameSaved();
       String filePath = lastThirdCharString(eosFileUpload.getFilePath());
       String downPath =RuoYiConfig.getUploadPath()+File.separator+filePath+File.separator+saveName;
       System.out.println(downPath);
       Long downloadCount= eosFileUpload.getDownloadCount();
       //设置新的下载日期和下载次数
       eosFileUpload.setDownloadDate(new Date());
       eosFileUpload.setDownloadCount(downloadCount+1);

       try {
           //下载文件
           byte[] data = Files.readAllBytes(Paths.get(downPath));
           ByteArrayResource resource = new ByteArrayResource(data);
           //修改文件下载日期和下载次数
           eosFileUploadService.updateEosFileUpload(eosFileUpload);

           return ResponseEntity.ok()
               .header(HttpHeaders.CONTENT_DISPOSITION)
               .contentType(MediaType.APPLICATION_OCTET_STREAM)
               .contentLength(data.length)
               .body(resource);
       }catch (NoSuchFileException e){
           //没有找到文件时,返回空参
           return new ResponseEntity("",HttpStatus.OK);
       }
   }
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值