«

微擎上传远程附件

时间:2024-4-30 10:58     作者:杨佳乐     分类: PHP


微擎上传远程附件 注:需要 load->func('file');

elseif ($operation == 'wxupload') {
    load()->func('file');
    $account_api = WeAccount::create();

    $data = array('err' => 0, 'msg' => '', 'imgUrl' => '');
    //access_token
    $sAccessToken = $account_api->getAccessToken();
    $sMediaId = trim($_GPC['mediaId']);
    if (!$sMediaId) {
        $data['msg'] = '参数错误,请重新选择图片上传!';
        echo json_encode($data);
        die;
    }
    $sUrl = 'https://api.weixin.qq.com/cgi-bin/media/get?access_token=' . $sAccessToken . '&media_id=' . $sMediaId;

    //文件名称
    $folder = IA_ROOT . '/' . $_W['config']['upload']['attachdir'] . "/images/{$_W['uniacid']}" . '/' . date('Y/m/');
    $filepath = "images/{$_W['uniacid']}" . '/' . date('Y/m/');
    //$filename = date("ymdhis",time()).".jpg";
    !is_dir($folder) && @mkdir($folder, 0755, true);
    //$new_file = $filepath.$filename;
    $filename = random(30) . '.' . 'jpg';
    //$sImgPath = date('Y',time()).'/'.date('md',time()). '/'.time(). '.jpg';
    //$sImgName =  PHPCMS_ROOT.'/front/public/uploadfile/' .$sImgPath;

    $oFileInfo = downloadWeixinFile($sUrl); //downloadWeixinFile
    if ($oFileInfo['body']) {
        saveWechatFile($folder, $filename, $oFileInfo['body']);
        if (!empty($_W['setting']['remote']['type'])) {
            $original_img = $filepath . $filename;

            $remotestatus = file_remote_upload($original_img);
            if (is_error($remotestatus)) {
                //file_delete($pathname);
                $result['error'] = 1;
                $result['message'] = '远程附件上传失败,请检查配置并重新上传';
                die(json_encode($result));
            } else {
                file_delete($original_img);
            }
        }
        $data['imgUrl'] = $filepath . $filename;
        echo json_encode($data);
        die;
    } else {
        $data['msg'] = '图片上传失败!';
        echo json_encode($data);
        die;
    }
}

function downloadWeixinFile($url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_NOBODY, 0);    //只取body头
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $package = curl_exec($ch);
    $httpinfo = curl_getinfo($ch);
    curl_close($ch);
    $imageAll = array_merge(array('header' => $httpinfo), array('body' => $package));
    return $imageAll;
}

function saveWechatFile($newfolder, $filename, $filecontent) {
    createFolder($newfolder);
    $local_file = fopen($newfolder . "/" . $filename, 'w');
    if (false !== $local_file) {

        if (false !== fwrite($local_file, $filecontent)) {

            fclose($local_file);
        }
    }
}