<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Request;
use think\Session;
use app\index\model\Member;
class Uploads extends Controller
{
public function _initialize()
{
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: AuthToken, Origin, X-Requested-With, Content-Type, Accept, Authorization");
header('Access-Control-Allow-Methods: POST,GET,PUT,DELETE');
}
//图片上传
public function uploads2($dir = '/uploads/index/upload/')
{
$file = request()->param('pic');
if (!$file) {
return json(['status'=>0,'msg'=>'请上传图片']);
} else {
$info = $file->validate(['size' => 2097152,'ext' => 'jpg,png,gif,jpeg'])->move(ROOT_PATH . '/public' . DS . $dir);
if (!$info) {
return json(['status'=>0,'msg'=>$file->getError()]);
} else {
$path = str_replace('\\', '/', Request()->domain() . $dir . $info->getSaveName());
return json(['status'=>1,'msg'=>'上传成功','url'=> $path ]);
}
}
}
//图片64位上传
public function uploads()
{
//图片的base64文件
$base64_img = input('post.pic');
//存放在当前目录的uploads文件夹下
$up_dir = './uploads/';
//判断是否存在文件,不存在创建
if (!file_exists($up_dir)) {
mkdir($up_dir, 0777);
}
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)) {
$type = $result[2];
//判断是否是图片格式
if (in_array($type, array('pjpeg', 'jpeg', 'jpg', 'gif', 'bmp', 'png'))) {
$new_file = $up_dir . date('YmdHis_') . '.' . $type;
if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_img)))) {
//图片的uploads/路径
$img_path = str_replace('../../..', '', $new_file);
$request = Request::instance();
$img = ltrim($img_path,'.');
//全部路径
$path = $request->domain() . $img_path;
// msg('ok', '图片上传成功', $path);
return json(['status'=>1,'msg'=>'上传成功','url'=> $path ]);
} else {
// msg('no', '图片上传失败');
return json(['status'=>0,'msg'=>'图片上传失败']);
}
} else {
//文件类型错误
// msg('no', '图片上传类型错误');
return json(['status'=>0,'msg'=>'图片上传类型错误']);
}
} else {
//文件错误
//msg('no', '文件错误');
return json(['status'=>0,'msg'=>'文件错误']);
}
}
}