Java读取第三方接口文件流返回前端预览、或保存文件

 Java读取第三方接口文件流返回前端预览

第三方接口返回文件流,将文件流返回我们应用前端实现预览文件功能

package com.example.demo;

import cn.hutool.core.util.IdUtil;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import static org.apache.catalina.manager.Constants.CHARSET;

@RestController
@RequestMapping("file")
public class TestController {

    /**
     * 前端下载文件
     * @param response
     * @throws UnsupportedEncodingException
     */
    @GetMapping(value = "/test1")
    public void test(HttpServletResponse response) throws UnsupportedEncodingException {
        // 设置编码
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("test.pdf", "UTF-8"));
        String path = "D://test.pdf";
        try {
            FileInputStream in = new FileInputStream(new File(path));
            FileCopyUtils.copy(in, response.getOutputStream());
        } catch (FileNotFoundException e) {
            System.out.println("文件不存在");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 前端预览文件
     * @param response
     * @throws IOException
     */
    @RequestMapping("download")
    public void download(HttpServletResponse response) throws IOException {
        String filePath = "D:\\test.pdf";
        System.out.println("filePath:" + filePath);
        File f = new File(filePath);
        if (!f.exists()) {
            response.sendError(404, "File not found!");
            return;
        }
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
        byte[] bs = new byte[1024];
        int len = 0;
        response.reset(); // 非常重要
        URL u = new URL("file:///" + filePath);
        String contentType = u.openConnection().getContentType();
        response.setContentType(contentType);
        response.setHeader("Content-Disposition", "inline;filename="
                + "test.pdf");
        // 文件名应该编码成utf-8,注意:使用时,我们可忽略这句
        OutputStream out = response.getOutputStream();
        while ((len = br.read(bs)) > 0) {
            out.write(bs, 0, len);
        }
        out.flush();
        out.close();
        br.close();
    }

    /**
     * 调用第三方流接口, 将文件保存到本地、读取本地文件返回前端预览
     * @param response
     * @throws IOException
     */
    @RequestMapping("test2")
    public void test2(HttpServletResponse response) throws IOException {
        HttpURLConnection urlConnection = null;
        FileOutputStream fileOutputStream;
        InputStream inputStream;
        String fileName = IdUtil.nanoId();
        try {
            URL url = new URL("http://localhost:8080/file/download");
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("POST");
            urlConnection.setConnectTimeout(20000);
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setUseCaches(false);
            urlConnection.setRequestProperty("Content-Type", "application/json; charset=" + CHARSET);
            urlConnection.connect();

            File file = new File("D://"+fileName+".pdf");
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            if (!file.exists()) {
                file.createNewFile();
            }
            inputStream = urlConnection.getInputStream();
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
            fileOutputStream = new FileOutputStream("D://"+fileName+".pdf");
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);

            byte[] buf = new byte[4096];
            int length = bufferedInputStream.read(buf);
            while (-1 != length) {
                bufferedOutputStream.write(buf, 0, length);
                length = bufferedInputStream.read(buf);
            }
            bufferedInputStream.close();
            bufferedOutputStream.close();
        } catch (Exception e) {
            System.out.println("getFile error: " + e);
        } finally {
            if (null != urlConnection) {
                urlConnection.disconnect();
            }
        }
        String filePath = "D://"+fileName+".pdf";
        File f = new File("D://"+fileName+".pdf");
        if (!f.exists()) {
            response.sendError(404, "File not found!");
            return;
        }
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
        byte[] bs = new byte[1024];
        int len = 0;
        response.reset(); // 非常重要
        URL u = new URL("file:///" + filePath);
        String contentType = u.openConnection().getContentType();
        response.setContentType(contentType);
        response.setHeader("Content-Disposition", "inline;filename="
                + fileName + ".pdf");
        // 文件名应该编码成utf-8,注意:使用时,我们可忽略这句
        OutputStream out = response.getOutputStream();
        while ((len = br.read(bs)) > 0) {
            out.write(bs, 0, len);
        }
        out.flush();
        out.close();
        br.close();
    }

    /**
     * 调用第三方流接口, 将文件流返回前端预览
     * @param request
     * @param response
     */
    @RequestMapping("test3")
    public void test3(HttpServletRequest request, HttpServletResponse response) {
        HttpURLConnection urlConnection = null;
        InputStream inputStream;
        try {
            URL url = new URL("http://localhost:8080/file/download");
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("POST");
            urlConnection.setConnectTimeout(20000);
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setUseCaches(false);
            urlConnection.setRequestProperty("Content-Type", "application/json; charset=" + CHARSET);
            urlConnection.connect();
            inputStream = urlConnection.getInputStream();
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
            byte[] buf = new byte[4096];
            int length = bufferedInputStream.read(buf);
            ServletOutputStream out = response.getOutputStream();
            while (-1 != length) {
                out.write(buf, 0,length);
                length = bufferedInputStream.read(buf);
            }
            out.flush();
            out.close();
            bufferedInputStream.close();
        } catch (Exception e) {
            System.out.println("getFile error: " + e);
        } finally {
            if (null != urlConnection) {
                urlConnection.disconnect();
            }
        }
    }
}

  • 3
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
使用iText生成PDF文件需要以下几个步骤: 1. 引入iText库 在项目中引入iText库,可以通过Maven等构建工具导入依赖,也可以手动下载jar包导入。 2. 创建PDF文档 使用iText创建一个PDF文档对象,如下所示: ``` Document document = new Document(); ``` 3. 创建PDF输出 创建一个输出,将PDF文档内容输出到指定的文件或者网络中,如下所示: ``` PdfWriter.getInstance(document, new FileOutputStream("output.pdf")); ``` 4. 打开文档 打开文档,开始编辑内容,如下所示: ``` document.open(); ``` 5. 编辑文档 编辑文档内容,可以插入文字、图片、表格等元素,也可以设置页面大小、边距等属性,具体使用方法见iText官方文档。 6. 关闭文档 编辑完成后,关闭文档,如下所示: ``` document.close(); ``` 完整代码示例: ``` Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream("output.pdf")); document.open(); document.add(new Paragraph("Hello World!")); document.close(); ``` 根据调用第三方接口返回文件生成PDF文件,可以将文件读取到内存中,然后通过iText的Image类创建图片对象,将图片插入到PDF中,具体代码示例如下: ``` // 假设fileStream是调用第三方接口返回文件 InputStream fileStream = ...; // 创建PDF文档对象和PDF输出 Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream("output.pdf")); // 打开文档,开始编辑内容 document.open(); // 创建图片对象 Image image = Image.getInstance(IOUtils.toByteArray(fileStream)); // 设置图片大小 image.scaleAbsolute(400, 400); // 插入图片到PDF中 document.add(image); // 关闭文档 document.close(); ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值