今天,上線一個客戶網站以後(使用的是廣州新一代虛擬空間)發如今讀取上傳的pdf文件的時候讀取錯誤,經過直接在瀏覽器輸入文件地址的時候發現文件地址被重定向了(呵呵!),結果就是pdf文件源由本地直接變成了跨域獲取。解決問題吧!php
一、pdf.js獲取文件的方法html
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項目上摘下的大概是有三種方式前端
前面兩種方法只能獲取同源文件,第三種方法就是我須要的跨域獲取文件方法了。git
二、經過後臺(php)獲取文件而且將其轉換成文件流返回給前端github
<?php
//直接使用file_get_contents獲取再輸出就行
$file = file_get_contents($url); echo $file;
?>
三、pdf.js經過ajax同步請求獲取文件流web
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; }
這個方法有問題:一、php服務器要支持文件讀取(能夠經過修改php配置文件前提是有這個修改權限)ajax
二、php讀取並輸出文件執行時間比較長跨域