vue+springboot通过post请求实现文件下载

前端vue

downFile () {
      let checkNodes = this.$refs.tree4.getCheckedNodes()
      this.checkNodes = []
      for (let i = 0; i < checkNodes.length; i++) {
        if (!checkNodes[i].children) {
          this.checkNodes.push(checkNodes[i].name)
        }
      }
      if (this.checkNodes.length > 0) {
        let str = this.checkNodes.join(',')
        let param = {
          'fileName': str
        }
        http.download(this.managerBaseURL, '/downloadFile', param, (response) => {}, 5 * 1000 * 1000)
      } else {
        this.$message({
          showClose: true,
          type: 'error',
          message: '请选择文件'
        })
      }
    }

封装http.download

download (baseURL, url, data, callback, timeout) {
    return axios({
      baseURL: baseURL,
      method: 'post',
      url,
      data: data,
      responseType: 'blob',//设置responseType为blob
      timeout: timeout
    }).then(
      (response) => {
        if (response.headers['content-type'] === 'APPLICATION/OCTET-STREAM') { 
          let filename = 'result.zip'
          //response.data为下载的文件数据
          let url = window.URL.createObjectURL(new Blob([response.data]))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', filename)
          document.body.appendChild(link)
          link.click()
        }
      }
    )
  }

后端下载方法

@RequestMapping(value = "downloadFile", method = RequestMethod.POST)
	public void downloadFile(@RequestBody DownloadFileDTO downloadFileDTO, HttpServletResponse response) throws IOException {

		response.setContentType("APPLICATION/OCTET-STREAM");
		ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
		// 获取文件存储路径(绝对路径)
		try {
			String fileName = downloadFileDTO.getFileName();
			String[] filePaths = fileName.split(",");
			for (String path : filePaths) {
				File file = new File(path);
				ZipUtils.doCompress(file.getCanonicalPath(), out);		//打包压缩
				response.flushBuffer();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			out.close();
		}
	}

 

你可能感兴趣的:(java,vue,文件下载,post请求)