vue+java下载文件实现

该文章展示了如何在Vue应用中调用Java后端接口下载文件。前端使用`axios`进行GET请求,设置`responseType`为`blob`,然后创建`a`标签模拟点击下载。后端使用`HttpServletRequest`和`HttpServletResponse`处理文件流,设置响应头以触发浏览器下载。
摘要由CSDN通过智能技术生成
  1. vue前端代码如下

1.1js代码

export function downloadExcelFile (params) {
  return request({
    url: 'api/channel/downloadExcelFile',
    method: 'get',
    responseType: 'blob', 
    params: params
  })

1.1vue引用

download (file) {
      let param = {
        'pdfPatch': file.url
      }
      api.downloadExcelFile(param).then(res => {
        var fileName = file.name
        const blob = new Blob([res])
        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)
        }
      })
    }

2.java接口代码

    @RequestMapping(value = "/downloadExcelFile")
    public void getFileInputStream(String pdfPatch, HttpServletRequest request,HttpServletResponse response) throws Exception {
        BufferedInputStream bis=null;
        BufferedOutputStream bos=null;
        try {
            File file = new File(pdfPatch);
            FileInputStream fis = new FileInputStream(file);
            response.setContentType("application/x-msdownload;");
            response.setHeader("Content-disposition", "attachment;filename=" + file.getName());
            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buffer = new byte[2048];
            int len;
            while ((len = bis.read(buffer, 0, buffer.length)) != -1) {
                bos.write(buffer, 0, len);
                bos.flush();
            }
            if (bis != null) {
                bis.close();
            }
            if (bos != null) {
                bos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (bis != null) {
                bis.close();
            }
            if (bos != null) {
                bos.close();
            }
        }

    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值