vue springboot前后端分离 文件预览

vue springboot前后端分离 文件预览,第1张

vue springboot前后端分离 文件预览 vue前端代码
    methods: {
      getfile() {
        this.ylLoading = true;
        const userReqData = {
          contractNum: this.formObj.contractNum
        }
        crudBilling.getfile(userReqData).then(res => {
          this.ylLoading = false;
          let blob = new Blob([res], {
            type: 'application/pdf' // 后台返回 pdf 类型的文件,如果是其他文件,可以根据MIME表来选择对应的文件类型
          })
          let fileName = Date.parse(new Date()) + '.pdf'
          if (window.navigator.msSaveOrOpenBlob) {
            navigator.msSaveBlob(blob, fileName)
          } else {
            var link = document.createElement('a')
            link.href = window.URL.createObjectURL(blob)
            link.download = fileName
            //打开新的标签页,渲染pdf文件
            window.open(link)
            //释放内存,使的链接只能打开一次。保证安全性。
            window.URL.revokeObjectURL(link.href)
          }
        }).catch(message => {
          this.ylLoading = false;
        });
      }
    }
springboot接口代码
    
     @NeedLog
     @GetMapping("/getFile")
     @PreAuthorize("@el.check('contract:getFile')")
     public void getFile(@RequestParam Long id,HttpServletResponse response)throws Exception{
       contractService.getFile(id,response);
    }
    @Override
    public void getFile(Long id, HttpServletResponse response) throws Exception {
        Contract contract = contractRepository.findById(id);
        if (contract == null) {
            return;
        }
        String url = contract.getUrl();
        File file = new File(url);
        if (file.exists()) {
            response.addHeader("Content-Disposition", "inline;fileName=" + java.net.URLEncoder.encode(file.getName(), "UTF-8"));
            response.setContentType("application/octet-stream;");
            response.setHeader("Content-Length",""+file.length());
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            byte[] buff = new byte[1024];
            OutputStream os = response.getOutputStream();
            try {
                int i;
                while ((i = bis.read(buff)) != -1) {
                    os.write(buff, 0, i);
                }
            } catch (IOException e) {
                log.error("下载pdf异常", e);
            } finally {
                os.flush();
                os.close();
            }
        }


    }

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5706858.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存