原文地址:http://www.cnblogs.com/JimmyBright/p/7681092.html
思路:js獲取遠端資源的blob會涉及到跨域的問題,所以需要中轉一下,具體是使用php的curl獲取
1 /** 2 * @desc 轉發獲取圖片防止前端跨域取不到資源 3 * @author Jimmy 4 * @date 2017-10-13 5 */ 6 public function actionGetimage() 7 { 8 header("Content-Type:image"); 9 $url = $this->getParam('url'); 10 $curl = curl_init(); 11 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 12 curl_setopt($curl, CURLOPT_TIMEOUT, 500); 13 curl_setopt($curl, CURLOPT_URL, $url); 14 $res = curl_exec($curl); 15 curl_close($curl); 16 echo $res; 17 }
JS裡可以在utils裡定義個公用方法 action為Yii框架裡對應的action路徑,fileUrl為一個靜態的遠端網路圖片
1 //獲取跨域的檔案Blob格式 2 function getRemoteImageBlob(action, fileUrl, callBack) { 3 let host = store.state.APIURL 4 let url = host + action + "?url=" + fileUrl 5 let xhr = new XMLHttpRequest() 6 xhr.open("GET", url) 7 xhr.responseType = "blob" 8 xhr.onload = () => { 9 callBack(xhr.response) 10 } 11 xhr.send() 12 }