JAVA url转二进制流(接收PDF)

    @RequestMapping("/PDF")
    @ResponseBody
    public synchronized void PDF(HttpServletRequest req,HttpServletResponse res,String bxCaseId) throws Exception {
        OutputStream out = null;
        try {
//这里是获取url的,业务需要就不改了,可以无视。
            String pdfPath = (String)approvalContractService.getPdf(bxCaseId).getMap().get("CONTRACT_FILE_URL");
            if(Strings.isEmpty(pdfPath)){
                throw new Exception();
            }
            URL url = new URL(pdfPath);
            URLConnection conn = url.openConnection();
            InputStream in = conn.getInputStream();
            out = res.getOutputStream();
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            int ch;
            while ((ch = in.read()) != -1) {   
                swapStream.write(ch);
            }
            res.setContentType("application/pdf;charset=UTF-8");
            res.setCharacterEncoding("UTF-8");
             
            swapStream.writeTo(out);
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(out!=null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容