pdf 配置预览

该博客主要介绍了如何实现PDF文件的预览功能,包括从请求参数获取文件路径,进行登录校验,数据权限判断,以及文件不存在时的错误处理。同时,代码展示了如何根据文件类型选择在线打开或下载方式,并设置了相应的内容类型和Disposition头。
摘要由CSDN通过智能技术生成

pdf 配置预览

比较简单,直接上代码

    @Resource
    private IProductService productService;
    @Value("${npi.default-url}")
    private String domain;
  
    @RequestMapping(value = "/preview", method = RequestMethod.GET)
    @LogApi(value = "preview")
    @ApiOperation(value = "预览文件", notes = "预览")
    public void preview(@RequestParam("path") String path, @RequestParam("npiProductId") String npiProductId, HttpServletRequest request, HttpServletResponse response) throws IOException {

        // 登录校验
        String username = JwtUtil.getUsername();
        if (StringUtils.isEmpty(username)) {
            String redirectPath = "/data-center/product-info/product-od-picture?action=preview&fileName=" + path + "&npiProductId=" + npiProductId;
            response.sendRedirect(domain + redirectPath);
        }

        // 数据权限判断
        boolean validateDataAuthority = validateDataAuthority(npiProductId, request);
        if (!validateDataAuthority) {
            throw new BusinessException("you have no auth to view the file!");
        }

        preview(path, response);
    }

    private boolean validateDataAuthority(String npiProductId, HttpServletRequest request) {
        if (StringUtils.isEmpty(npiProductId)) {
            throw new BusinessException("npiProductId can not empty!");
        }

        List<Product> list = productService.getAuthProduct(request);
        Optional<Product> first = list.stream().filter(product -> npiProductId.equals(product.getId())).findFirst();
        if (first.isPresent()) {
            return first.get().getHaveReadAuth();
        }
        return false;
    }

    private void preview(String path, HttpServletResponse response) {
        try {
            // 1. 找到文件路径
            String filepath = springBootPlusProperties.getUploadPath() + path;
            log.info("file path is ===> " + filepath);
            File file = new File(filepath);
            if (!file.exists()) {
                response.sendError(404, "File not found!");
                return;
            }
            previewWrapper(response, filepath, file);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void previewWrapper(HttpServletResponse response, String filepath, File file) throws IOException {
        resetResponseHeader(response, filepath, file);

        BufferedInputStream br = new BufferedInputStream(new FileInputStream(file));
        byte[] bs = new byte[1024];
        int len = 0;
        OutputStream out = response.getOutputStream();
        while ((len = br.read(bs)) > 0) {
            out.write(bs, 0, len);
        }
        out.flush();
        out.close();
        br.close();
    }

    private void resetResponseHeader(HttpServletResponse response, String filepath, File file) throws IOException {
        response.reset();

        String filename = file.getName();
        String suffix = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();

        // 在线打开方式
        if (ArrayUtil.contains(CommonConstant.PDF_TYPE, suffix)) {
            URL u = new URL("file:///" + filepath);
            String contentType = u.openConnection().getContentType();
            response.setContentType(contentType);
            response.setHeader("Content-Disposition", "inline;filename=" + filename);
        } else {
            // 纯下载方式
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值