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();
            }
        }


    }
Spring BootVue 前后端分离架构中,实现文件预览可以通过前端发送请求获取文件的 URL,然后在前端使用相关插件或组件进行文件预览。 下面是一种可能的实现方式: 1. 后端实现: - 在 Spring Boot 中配置静态资源路径,将存储文件文件夹路径设置为静态资源路径。例如,可以在 `application.properties` 文件中添加以下配置: ``` spring.resources.static-locations=file:/path/to/files/ ``` - 后端提供一个接口,用于返回文件的URL。可以在控制器中编写如下代码: ```java @RestController public class FileController { @Value("${spring.resources.static-locations}") private String staticResourcePath; @GetMapping("/api/file/{fileName}") public ResponseEntity<Resource> getFile(@PathVariable String fileName) throws IOException { Path filePath = Paths.get(staticResourcePath + fileName); Resource resource = new UrlResource(filePath.toUri()); if (resource.exists() && resource.isReadable()) { return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"") .body(resource); } else { // 文件不存在或无法读取 return ResponseEntity.notFound().build(); } } } ``` 2. 前端实现: - 在 Vue 组件中,使用 axios 或其他网络请求库发送 GET 请求,获取文件的 URL。例如: ```javascript import axios from 'axios'; // 在组件中调用接口获取文件 URL axios.get('/api/file/fileName.pdf') .then(response => { const fileUrl = response.data; // 使用文件预览插件或组件进行预览 // 例如,可以使用 pdf.js 进行 PDF 文件预览 // 或者使用 <img> 标签显示图片、使用 <video> 标签播放视频等 }) .catch(error => { console.error(error); }); ``` 需要注意的是,上述代码只是一种简单的实现方式,具体的预览方式和插件选择取决于你要预览文件类型。你可以根据实际需求选择合适的插件或组件来实现文件预览功能,例如 pdf.js、viewer.js 等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值