//引入
use think\Image; /*
* $name为表单上传的name值
* $filePath为为保存在入口文件夹public下面uploads/下面的文件夹名称,没有的话会自动创建
* $width指定缩略宽度
* $height指定缩略高度
* 自动生成的缩略图保存在$filePath文件夹下面的thumb文件夹里,自动创建
* @return array 一个是图片路径,一个是缩略图路径,如下:
* array(2) {
["filepath"] => string(57) "uploads/img/20171211\3d4ca4098a8fb0f90e5f53fd7cd71535.jpg"
["thumbimgpath"] => string(63) "uploads/img/thumb/20171211/3d4ca4098a8fb0f90e5f53fd7cd71535.jpg"
}
*/
protected function uploadFile($name,$filePath,$width = 0,$height = 0)
{
$file = request()->file($name);
if($file){
$filePaths = ROOT_PATH . 'public' . DS . 'uploads' . DS . $filePath;
if (!file_exists($filePaths)) {
mkdir($filePaths, 0777, true);
}
$info = $file->move($filePaths);
if ($info) {
$imgpath = $filePaths . '/' . $info->getSaveName();
$url_path = '/uploads/'. $filePath . '/' . $info->getSaveName();
$image = \think\Image::open($imgpath);
$date_path = $filePaths . '/thumb/' . date('Ymd');
$thumb_url = '/uploads/'. $filePath .'/thumb/' . date('Ymd');
if (!file_exists($date_path)) {
mkdir($date_path, 0777, true);
}
$thumb_path = $date_path . '/' . $info->getFilename();
$thumb_url_path = $thumb_url . '/' . $info->getFilename();
$image->thumb($width, $height)->save($thumb_path);
$uploadinfo = ['code' => 0, 'data' => ['filepath' => $url_path,'thumbimgpath'=>$thumb_url_path],'msg'=>''];
return json_encode($uploadinfo);
}else{
// 上传失败获取错误信息
return json_encode(['code'=>-1,'data'=>'','msg'=>$file->getError()]);
}
}
}
//调用
www.xxx.com/api/goods/uploadFile
$res = uploadFile('image','goods',200,200);
var_dump($res);