一、单个文件下载

思路很简单: 当页面加载时,那么下面的href里就会执行downloadFile()这个函数,然后 downloadFile()里面访问后台接口,得到文件流,然后赋值给href属性,所以当我们点击“下载”时,浏览器就会去下载文件了

前端代码如下:

<el-link type="primary" :href="downloadFile(scope.row.attachment)" v-show="false" :id="scope.row.id">下载 </el-link>

  //单个文件下载
      downloadFile(file){   
        return "common/file/downLoad?id="+file.id+"&fileName="+file.name;
      },

后端代码如下:具体代码没给,反正要给前端返回ResponseEntity<byte[]>类型的数据

@RequestMapping("/downLoad")
	 public ResponseEntity<byte[]> downLoad(HttpServletResponse response,FileParam fileParam ) throws IOException {
	 //具体代码请百度
	 }

二、批量压缩下载

前端代码如下:

下面这个是api.js文件下的函数

 batchDownload(ids){
    return request({
      url: '/common/file/batchDownload',
      method: 'get',
      responseType: 'blob',
      params: {
        ids:ids
      }
    })
  },

具体页面如下:

 <el-button @click="multiplyDownload()" size="mini" type="primary">批量下载</el-button>
   //批量下载
      multiplyDownload(){
        this.multiplySelect=[];
          if(this.multiplyObjSelect.length==0){
            this.$message({
              type: "error",
              message: "sorry,你还没有勾选任何文件呢!"
            });
            return;
          }  downloadApi.batchDownload(this.multiplySelect.join(',')).then(async res=>{
          let title = "批量下载.zip";
          const uA = window.navigator.userAgent;
          const isIE = /msie\s|trident\/|edge\//i.test(uA) && !!("uniqueID" in document || "documentMode" in document || ("ActiveXObject" in window) || "MSInputMethodContext" in window);
          const link = document.createElement('a')
          let tableList = []
          let index = 1;
          let blob = new Blob([res]);
          link.style.display = 'none'
          link.href = URL.createObjectURL(blob);
          link.setAttribute('download', title)
          document.body.appendChild(link)
          if (isIE) {
            // 兼容IE11无法触发下载的问题
            navigator.msSaveBlob(blob, title);
          } else {
            link.click();
          }
          document.body.removeChild(link)
        })
      },

后台代码:
controller层:

/**
     * 批量下载文件
     */
    @GetMapping("/batchDownload")
    public ResponseEntity<byte[]> batchDownload(HttpServletRequest request,String ids)  {
        String[] split = ids.split(",");
        List<String> idList = Arrays.asList(split);
        ResponseEntity<byte[]> responseEntity = null;
        try {
            responseEntity = fileService.batchDownload(idList );
        } catch (Exception e) {
        }
        return responseEntity;
    }

sevice层的代码如下

/**
     * 批量下载文件
     * @param
     * @return
     */
    @Override
    public ResponseEntity<byte[]> batchDownload(List<String> idList) {
        // ---------------------------压缩文件处理-------------------------------
        ByteArrayOutputStream OutputStream = new ByteArrayOutputStream();
        // 下面的FileVo是我们自定义写的一个实体类类
        List<FileVo> fileVos = queryFiles(idList);
        // 压缩文件
        FastDFSUtil.multiplyFileToZIP(fileVos , OutputStream );
        // ---------------------------压缩文件处理-------------------------------
        HttpHeaders headers = new HttpHeaders();
        String fileName = null;
        try {
            fileName = "批量下载.zip";
            fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", fileName);// 文件名称
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(byteOutPutStream.toByteArray(), headers,
                HttpStatus.CREATED);
        return responseEntity;
    }

现在公众号迁移到这个啦, 不要迷路了,慕仔们,加油哦!
在这里插入图片描述
接下来的一段时间,我会专注Java技术栈,计算机网络,数据结构和算法,操作系统,设计模式,计算机组成原理,数据库原理,设计模式来做分享,欢迎你们和我一起学习,一起提高,Fighting!

Logo

前往低代码交流专区

更多推荐