1. 程式人生 > >pdf.js如何跨域讀取pdf文件?

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

earch decode sed 廣州新一代 pla ont end php服務器 ech

今天,上線一個客戶網站之後(使用的是廣州新一代虛擬空間)發現在讀取上傳的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讀取並輸出文件執行時間比較長

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