获取远程图片的Blob资源
原文地址: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 }