pdf.js跨域解决方法——远程加载pdf

思路:通过将需要浏览的pdf通过后台转为文件流传给前端,来解决跨域问题。

js代码写在viewer.html里,放到引用pdf.js的位置前面

js代码,来接收文件流:

后台,我写通过java了一个servlet来把文件转成文件流:

package main;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

@WebServlet(name = "Convert")
public class Convert extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/pdf");
        response.setHeader("Access-Control-Allow-Origin", "*"); // 解决请求头跨域问题
        ServletOutputStream sos = response.getOutputStream();
        String destUrl = "http://39.107.117.248/pdf-store/caseFile.pdf";
        URL url = new URL(destUrl);
        HttpURLConnection httpUrl = (HttpURLConnection)url.openConnection();
        // 连接指定的网络资源
        httpUrl.connect();
        // 获取网络输入流
        BufferedInputStream bis = new BufferedInputStream(httpUrl.getInputStream());
        int b;
        while ((b = bis.read())!= -1){
            sos.write(b);
        }
        sos.close(); // 这里有点和c语言里的读取文件有点像
        bis.close();
    }
}

参考链接:https://blog.csdn.net/anciend/article/details/80062213,感谢Anciend的分享

你可能感兴趣的:(web前端开发)