/**
 * base64上传文件
 */
public function upload_base64() {
    if($this->request->isPost()) {
        $param = $this->request->param();
        $validate = new \think\Validate([
            'base64_img' => 'require',
        ]);
        $validate->message([
            'base64_img.require' => '缺少图片base64数据!',
        ]);
        if (!$validate->check($param)) {
            $this->error($validate->getError());
        }
        $path = '/uploads';
        $attachment = $this->base64_image_content($param['base64_img'],$path);
        if(!$attachment) {
            $this->error('上传失败');
        }
        $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
    }
}
/**
     * [将Base64图片转换为本地图片并保存]
     * @E-mial wuliqiang_aa@163.com
     * @TIME   2017-04-07
     * <a href="https://ask.fastadmin.net/u/22397" data-type="user" data-id="22397" data-toggle="popover" data-title="web">@WEB</a>    http://blog.iinu.com.cn
     * @param  [Base64] $base64_image_content [要保存的Base64]
     * @param  [目录] $path [要保存的路径]
     */
    private function base64_image_content($base64_image_content,$path){
        //匹配出图片的格式
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
            $file_path = date('Ymd',time())."/";
            $new_file = '.'.$path."/".$file_path;
            if(!file_exists($new_file)){
                //检查是否有该文件夹,如果没有就创建,并给予最高权限
                mkdir($new_file, 0777,true);
            }
            $new_file = $new_file.time().".jpg";

            $res =  file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)));
            if ($res){
                $img =   imagecreatefromjpeg($new_file);
                $params = array(
                    'admin_id'    => (int)session('admin.id'),
                    'user_id'     => (int)cookie('uid'),
                    'filename'    => time().".jpg",
                    'filesize'    => filesize($new_file),
                    'imagewidth'  => imagesx($img),
                    'imageheight' => imagesy($img),
                    'imagetype'   => 'jpg',
                    'imageframes' => 0,
                    'mimetype'    => 'image/jpeg',
                    'url'         => $path."/".$file_path.time().".jpg",
                    'uploadtime'  => time(),
                    'storage'     => 'local',
                    'sha1'        => hash_file('sha1',$new_file),
                    'extparam'    => '',
                );
                $attachment = new Attachment();
                $attachment->data(array_filter($params));
                $attachment->save();

                return $attachment;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }


点赞(67)

评论列表 共有 0 条评论

暂无评论
立即
投稿
发表
评论
返回
顶部
{__SCRIPT__}