UploadController.php 1.9 KB
<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/24
 * Time: 10:47
 */

namespace app\index\controller;


use cmf\controller\WeChatBaseController;
use EasyWeChat\Foundation\Application;

class UploadController extends WeChatBaseController
{
    public function wechat_upload()
    {

        $options = [
            'app_id' => config('wechat_config.app_id'),
            'secret' => config('wechat_config.secret'),
            'payment' => config('wechat_config.payment'),
        ];
        $app = new Application($options);
        $accessToken = $app->access_token;
        $access_token = $accessToken->getToken();
        $media = $this->request->param('media');
        $file = $this->getmedia($access_token, $media, 'wechat_img/' . date('Ymd'));
        $data = $file;
        if(empty($file)){
            $arr['code'] = 40000;
            $arr['msg'] = '上传失败';
        }else{
            $arr['code'] = 20000;
            $arr['msg'] = '上传成功';
            $arr['data'] = $data;
        }
        return json_encode($arr);
    }
    private function getmedia($access_token, $media_id, $foldername)
    {
        $url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" . $access_token . "&media_id=" . $media_id;
        if (!file_exists("./upload/" . $foldername)) {
            mkdir("./upload/" . $foldername, 0777, true);
        }
        $file_name = date('YmdHis') . rand(1000, 9999) . '.jpg';
        $targetName = './upload/' . $foldername . '/' . $file_name;
        $saveName = $foldername . '/' . $file_name;
        $ch = curl_init($url); // 初始化
        $fp = fopen($targetName, 'wb'); // 打开写入
        curl_setopt($ch, CURLOPT_FILE, $fp); // 设置输出文件的位置,值是一个资源类型
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_exec($ch);
        curl_close($ch);
        fclose($fp);
        return $saveName;
    }
}