微信JSSDK 实现打开摄像头拍照再将相片保存到服务器

在微信端打开手机摄像头拍照,将拍照图片保存到服务器上需要使用到微信的JSSDK接口,主要使用到了拍照或从手机相册中选图接口(chooseImage),上传图片接口(uploadImage)

参考资料:

https://mp.weixin.qq.com/wiki...

https://www.easywechat.com/do...

一:引入微信js

二:通过config接口注入权限验证配置

wx.config(wechat->js->config([
        'chooseImage',
        'uploadImage',
        'downloadImage'
    ])
    ?>
);

三:微信端拍照接口

wx.chooseImage({
    count: 1, // 默认9
    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
    success: function (res) {
        var localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
    }
});

四:将照片上传到微信服务器接口

 wx.uploadImage({
    localId: localIds, // 需要上传的图片的本地ID,由chooseImage接口获得
    isShowProgressTips: 1, // 默认为1,显示进度提示
    success: function (res) {
        var serverId = res.serverId; // 返回图片的服务器端ID
    },
    fail: function() {
       //上传图片到微信服务器失败
        return false;
    }
});

五:将微信服务器的图片下载到本地服务器

前端:

//url表示php接口地址
//serverId表示图片的服务器端ID
$.post(url, {'media_id':serverId}, function(data) {
    if (data.type == 'success') {
       //上传成功
        
    } else {
        //上传失败
        
    }
});

php(接口)

public function actionUpload()
{
    Yii::$app->response->format = Response::FORMAT_JSON;
    $request = Yii::$app->request;
    $mediaId = $request->post('media_id');
    if (empty($mediaId)) {
        return [
            'type' => 'error',
            'message' => '参数错误!'
        ];
    }
    //临时素材
    $temporary = Yii::$app->wechat->material_temporary;
    //创建服务器目录
    $path = 'wechat/' . date('Ymd',time()) . '/';
    $fullPath = Yii::getAlias('@webroot') . '/' . $path;
    if (!is_dir($fullPath)) {
        FileHelper::createDirectory($fullPath);
    }
    //设置图片名称
    $fileName = Yii::$app->getSecurity()->generateRandomString() . '-' . date('His',time());
    //将服务器端的临时素材下载到本地服务器
    $temporary->download($mediaId, $fullPath, $fileName);
    return [
        'type' => 'success',
        'url' => $path . $fileName . '.jpg',
    ];
}

前端代码整合





wechat->js->config([
    'chooseImage',
    'uploadImage',
    'downloadImage'
]);
$JS = <<registerJs($JS);
?>

根据如上代码就可以实现微信端打开摄像头拍照再将相片保存到服务器功能

你可能感兴趣的:(微信,php)