###
今天因為工作需要,完成了一個二維碼的生成圖片,並支持點擊下載的
###
控制器文件,相關代碼
1 // 生成二維碼 2 $url = action('Apih5\\VersionController@download', ['provider' => $request->channel]); 3 // 保存二維碼到本地,並返回二維碼 4 $qrcode = $this->app['version']->qrcode($url);
5 $dir_path = '../public/static/versionChannel/'; 6 $fileName = $request->channel.'.png'; 7 $qrcode = base64_decode( $qrcode); 8 // 保存到本地,如果不存在文件,則創建新的 9 $this->app['version']->saveVersionQrcode($qrcode, $dir_path, $fileName); 10 11 // 保存二維碼到本地,並返回二維碼 12 $qrcode = $this->app['version']->qrcode($request->channel, $url);
后台實現下載的控制器
1 <?php 2 3 namespace App\Http\Controllers\Apih5; 4 5 use Illuminate\Http\Request; 6 7 use App\Http\Requests; 8 use App\Http\Controllers\Controller; 9 10 class VersionController extends Controller 11 { 12 //版本二維碼下載 13 public function download($provider, Request $request) 14 { 15 // 下載二維碼 16 $contenttype = 'image/jpeg'; 17 $dir_path = '../public/static/versionChannel/'; 18 $fileName = $provider.'.png'; 19 $fileurl = $dir_path.$fileName; 20 21 header("Cache-control: private"); 22 header("Content-type: $contenttype"); //設置要下載的文件類型 23 header("Content-Length:" . filesize($fileurl)); //設置要下載文件的文件大小 24 header("Content-Disposition: attachment; filename=" . urldecode($fileName)); //設置要下載文件的文件名 25 26 readfile($fileurl); 27 28 } 29 }
方法所在文件
1 /** 2 * 生成二維碼 for apih5/VersionController 3 * @param [type] $id [description] 4 * @return [type] [description] 5 */ 6 public function qrcode($url) 7 { 8 $qrcode = new QrcodeHelper; 9 $qrcode = $qrcode->getVersionChannelQr($url); 10 11 return $qrcode; 12 } 13 14 /** 15 * 保存二維碼到本地文件夾 16 */ 17 public function saveVersionQrcode($qrcodeData, $dir_path, $fileName) 18 { 19 // 判斷目錄是否存在,不存在則生成 20 if (!file_exists($dir_path) ) { 21 mkdir("$dir_path",0777, true); 22 } 23 $fileurl = $dir_path.$fileName; 24 // 保存到本地,如果不存在文件,則創建新的 25 file_put_contents($fileurl, $qrcodeData, FILE_USE_INCLUDE_PATH); 26 }
前台試圖
顯示二維碼圖片的位置
1 <td> 2 3 <a href="{{ action('Apih5\\VersionController@download',['provider' => $version->channel]) }}" > 4 <img width="100px" src="{{url('/static/versionChannel/'.$version->channel.'.png')}}"/> 5 </a> 6 </td>