PHP最简洁实现上传图片
该上传接口放到controller里,返回的json格式是用于wangEditor编辑器的,非常好用上代码:
/**
* 上传图片
*/
public function uploadPic($req)
{
$data = array (
array(
"name"=>"",
"url" => "",
"alt" => "",
"href" => ""
)
);
$file = $_FILES['images'];
$rootPath = str_replace('\\','/',realpath(dirname(__FILE__).'/../../../'));
if ($file) {
//保存目录名
$uploadPath = "/upload/images/" . date('Y-m-d', time());
//随机文件名
$randName = $this->getRandName();
//文件的扩展名
$ext = pathinfo($file['name'],PATHINFO_EXTENSION);
//新文件名
$fileName = $randName. '.' . $ext;
//目标文件路径
$dest = $rootPath . $uploadPath .'/' . $fileName;
//文件夹不存在或者不是目录,创建文件夹
$folderPath = $rootPath . $uploadPath;
if (!file_exists($folderPath) || !is_dir($folderPath)) {
mkdir($folderPath, 0777, true);
}
//判断文件是否可写
if (!is_writeable($folderPath)) {
chmod($folderPath, 0777);
}
$data[0]['name'] = $fileName;
$data[0]['url'] = $uploadPath .'/' . $fileName;
$tmp = $file['tmp_name'];
if(is_uploaded_file($tmp)){
if(move_uploaded_file($tmp,$dest)){
$response = ['errno'=>0,'msg'=>'图片上传成功','data'=>$data];
exit(json($response));
}else{
$response = ['errno'=>-1,'msg'=>"图片上传失败",'data'=>$data];
exit(json($response));
}
}else{
$response = ['errno'=>-1,'msg'=>"不是可上传文件",'data'=>$data];
exit(json($response));
}
}
$response = ['errno'=>-1,'msg'=>"图片上传失败",'data'=>$data];
return json($response);
}
/**
* 随机文件名
*/
public function getRandName(){
$name = date('YmdHis');
for($i=0; $i<6; $i++){
switch(mt_rand(0,2)){
case 0:
$name .= chr(mt_rand(97,122)); //小a
break;
case 1:
$name .= chr(mt_rand(65,90)); //大A
break;
case 2:
$name .= mt_rand(0,9); //获取随机数
break;
}
}
return $name;
}
本站内容来源于作者发布和网络转载,如有版权相关问题请及时与我们取得联系,我们将立即删除。