JAVA 实现返回PDF文件流并进行下载

JAVA 实现返回PDF文件流并进行下载

首先确保本地存放pdf 保证通过路径可以拿到文件 我这边把pdf放在e盘下的目录

1.前台方法 原生ajax 发送请求返回文件流进行下载

 function downloadPdf() {
        //后台下载文件流地址 (自己定义)
        let url = prefix + "/result";
        let xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
        xhr.responseType = 'blob'; //返回类型blob
        //定义请求完成的处理函数,请求前也可以增加加载框/禁用下载按钮逻辑
        xhr.onload = function (res) {
            //请求完成
            let blob = this.response;
            let reader = new FileReader();
            reader.readAsDataURL(blob)
            reader.onload = function (e) {
                //创建a标签 模拟点击事件下载文件流
                const object = document.createElement('a');
                //下载的pdf名称
                object.download = '阿里巴巴Java开发手册终极版v1.3.0.pdf';
                object.href = e.target.result;
                $("body").append(object);    // 修复firefox中无法触发click
                object.click();
                $(object).remove();
            }
        }
        // 发送ajax请求
        xhr.send()
    }

2.后台方法

  @GetMapping("/result")
    public void result(HttpServletRequest request, HttpServletResponse response) throws IOException {
		//你的文件所存放的地址 我这边放在e盘下
        String pdfPath = "E:/阿里巴巴Java开发手册终极版v1.3.0.pdf";
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "xxx.pdf");
        FileUtils.writeBytes(pdfPath, response.getOutputStream());
        File file = new File(pdfPath);
        if (file.exists()) {
            DataOutputStream temps = new DataOutputStream(response.getOutputStream());
            DataInputStream in = new DataInputStream(new FileInputStream(pdfPath));
            byte[] b = new byte[2048];
            while ((in.read(b)) != -1) {
                temps.write(b);
                temps.flush();
            }
            in.close();
            temps.close();
        } else {
            log.error("文件不存在!");
        }
    }
 /**
     * 输出指定文件的byte数组
     * 
     * @param filePath 文件路径
     * @param os 输出流
     * @return
     */
    public static void writeBytes(String filePath, OutputStream os) throws IOException
    {
        FileInputStream fis = null;
        try
        {
            File file = new File(filePath);
            if (!file.exists())
            {
                throw new FileNotFoundException(filePath);
            }
            fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int length;
            while ((length = fis.read(b)) > 0)
            {
                os.write(b, 0, length);
            }
        }
        catch (IOException e)
        {
            throw e;
        }
        finally
        {
            if (os != null)
            {
                try
                {
                    os.close();
                }
                catch (IOException e1)
                {
                    e1.printStackTrace();
                }
            }
            if (fis != null)
            {
                try
                {
                    fis.close();
                }
                catch (IOException e1)
                {
                    e1.printStackTrace();
                }
            }
        }
    }

版权声明:本文为qq_37676492原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。