apicp.UploadHeadImg.php 1.62 KB
    <?php
    /**
     * 跨域处理
     */
    header('Access-Control-Allow-Origin:*');
    header("Access-Control-Allow-Methods:GET,POST");

    /**
     *  用户上传头像
     */

    include "Common/JsonResponse.php";
    include "Common/mysqlHelper.php";
    include "Common/WechatHelper.php";
    include "Common/Encrypter.php";

    // id,头像
    if (!isset($_POST['id']) || !isset($_POST['mediaId'])) {
        JsonResponse::error('传参错误');
    }

    // 姓名唯一
    $id = $_POST['id'];
    $mysql    = new mysqlHelper();
    $data     = $mysql->fetch("SELECT id FROM user WHERE id = ?", [$id]);
    if (!isset($data)) {
        JsonResponse::error('用户不存在');
    }
    // 获取头像数据,从微信临时素材图片中。
    $wechat = new WechatHelper();
    $img    = $wechat->getMedia($_POST['mediaId']);

    // 保存图片
    $filename    = time() . rand(1000, 9999) . ".jpg";
    $tarfilename = "/upload/" . $filename;
    $dir         = str_replace('\\', '/', realpath(dirname(__FILE__) . '/'));
    $dir         = rtrim($dir, '/party/phpapi/');
    $fp          = fopen($dir . $tarfilename, "w");
    fwrite($fp, $img);
    fclose($fp);

    // 组装用户需要的数据
    $headimg = 'http://' . $_SERVER['SERVER_NAME'] . $tarfilename;
    $time     = time();
    // pdo保存数据
    $updateSql = "UPDATE user SET headimg = '{$headimg}', created = {$time} WHERE id = {$id};";
    $rowCount  = $mysql->update($updateSql);

    if ($rowCount) {
        JsonResponse::result([
            'headimg' => $headimg
        ]);
    } else {
        JsonResponse::error('头像上传失败');
    }