pdf.js如何跨域读取pdf文件?

今天,上线一个客户网站之后(使用的是广州新一代虚拟空间)发现在读取上传的pdf文件的时候读取错误,通过直接在浏览器输入文件地址的时候发现文件地址被重定向了(呵呵!),结果就是pdf文件源由本地直接变成了跨域获取。解决问题吧!

1、pdf.js获取文件的方法

You can modify the defaultUrl app option in the web/app_options.js file or you can append the ?file= query string to the viewer URL, e.g. http://mozilla.github.com/pdf.js/web/viewer.html?file=compressed.tracemonkey-pldi-09.pdf. In the latter case, the PDF path/URL must be encoded using encodeURIComponent().

The viewer can be started without any PDF loaded by setting the defaultUrl app option to an empty string or by using the ?file= query string without any location specified. Use PDFViewerApplication.open(file) to load the PDF file later.

You can use raw binary data to open a PDF document: use Uint8Array instead of URL in the PDFViewerApplication.open call. If you have base64 encoded data, please decode it first -- not all browsers have atob or data URI scheme support. (The base64 conversion operation uses more memory, so we recommend delivering raw PDF data as typed array in first place.)

以上是从其github项目上摘下的大概是有三种方式

  • 设置defaultUrl
  • 通过路径后面带file参数   比如:http://mozilla.github.com/pdf.js/web/viewer.html?file=compressed.tracemonkey-pldi-09.pdf
  • 使用PDFViewerApplication.open打开Uint8Array获取的文件流形式

前面两种方法只能获取同源文件,第三种方法就是我需要的跨域获取文件方法了。

2、通过后台(php)获取文件并且将其转换成文件流返回给前端

<?php
//直接使用file_get_contents获取再输出就行
$file
= file_get_contents($url); echo $file;
?>

3、pdf.js通过ajax同步请求获取文件流

var PDFData = "";
var getUrl = "";
var baseUrl = "http://www.zdxhxfzxwx.com.img26752.200cdn.com:9898";
getUrl = baseUrl + getQueryString("filePath");
$.ajax({  
    type:"post",  
    async:false,  //
    contentType: "application/x-www-form-urlencoded",
    mimeType: 'text/plain; charset=x-user-defined',  
    url:"/plus/getFileToBinary.php",  
    success:function(data){  
       PDFData = data;  
    },
    data: {
      "url": getUrl,
    }
});  
var rawLength = PDFData.length;  
console.log(rawLength);
//转换成pdf.js能直接解析的Uint8Array类型,见pdf.js-4068  
var array = new Uint8Array(new ArrayBuffer(rawLength));    
for(i = 0; i < rawLength; i++) {  
  array[i] = PDFData.charCodeAt(i) & 0xff;  
}  
DEFAULT_URL = array; 
function getQueryString(name) { 
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); 
    var r = window.location.search.substr(1).match(reg); 
    if (r != null) return unescape(r[2]); 
    return null; 
}  

这个方法有问题:1、php服务器要支持文件读取(可以通过修改php配置文件前提是有这个修改权限)

        2、php读取并输出文件执行时间比较长

猜你喜欢

转载自www.cnblogs.com/linxingyun/p/9293455.html
今日推荐