设置了一个图片服务器专门用来存储图片
<?php
// +----------------------------------------------------------------------
// | Author: 陈荣 <812069449@qq.com>
// +----------------------------------------------------------------------
namespace Home\Controller;
use Think\Controller;
/**
* 文件上传接口类
*/
class IndexController extends Controller {
// 服务HOST 地址
private $serverHost;
public function __construct(){
parent::__construct();
$this->serverHost = 'http://file.study.com/';
}
/**
* 文件上传
* 类似表单上传方式
* @access public
* @param string POST.path 来源域名
* @param array FILES.imgFile 上传文件对象
* @return json 返回处理结果
*/
public function fileUpload(){
$path = I("post.path","",'trim');
if(empty($path)){
$array = array("error"=>1,"message"=>"路径不能为空!");
self::message($array);
}
// 解析路径
$basePath = preg_replace('/((http|https):\/\/)?\w+\.\w+\.\w+\//', '', $path);
$basePath = rtrim($basePath,"/");
$basePath = $basePath."/img/".date('Ymd',time());
if(empty($basePath)){
$array = array("error"=>1,"message"=>"路径解析错误");
self::message($array);
}
$upload = new \Think\Upload();// 实例化上传类
$upload->maxSize = 2097152 ;// 设置附件上传大小
$upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
$upload->rootPath = "./static/";
$upload->autoSub = true;
$upload->subName = $basePath;
// 上传文件
$info = $upload->uploadOne($_FILES['imgFile']);
if(!$info){
// 上传错误提示错误信息
$array = array("error"=>1,"message"=>$upload->getError());
self::message($array);
}else{
// 拼接跟地址
$info['newpath'] = $upload->rootPath.$info['savepath'].$info['savename'];
$status = self::imgResetSize($info);
// 判断是否压缩成功
if($status){
$array = array('error' =>0,'url'=>$this->serverHost.'/'.$basePath.'/'.$info['savename']);
self::message($array);
}else{
$array = array('error' =>1,'message'=> '图片压缩出错!');
self::message($array);
}
}
}
/**
* BASE64
* 编辑器 BASE64 方式
* @access public
* @param string POST.img 图片BASE64值
* @param string POST.type 文件保存的类型
* @param string POST.webdir 文件保存路径
* @return json 返回处理结果
*/
public function formUpload(){
// 获取数据
$post = I("post.","","trim");
// 判断参数
if(empty($post)){
$array = array('error' =>1,'message'=> '请传入参数!');
self::message($array);
}
// 判断图片内容
if(empty($post['img'])){
$array = array('error' =>1,'message'=> '图片内容不能为空!');
self::message($array);
}
// 判断文件大小
if(strlen($post['img'])>3103540){
$array = array('error' =>1,'message'=> '文件太大!');
self::message($array);
}
// 判断图片类型
if(empty($post['type'])){
$array = array('error' =>1,'message'=> '图片类型不能为空!');
self::message($array);
}
// 过滤文件类型
if(!in_array($post['type'], array('jpg', 'gif', 'png', 'jpeg'))){
$array = array('error' =>1,'message'=> '不支持的文件类型!');
self::message($array);
}
// 判断保存路径
if(empty($post['webdir'])){
$array = array('error' =>1,'message'=> '目录不能为空!');
self::message($array);
}
// 解析路径
$basePath = preg_replace('/((http|https):\/\/)?\w+\.\w+\.\w+\//', '', $post['webdir']);
$basePath = rtrim($basePath,"/");
$basePath = $basePath."/img/".date('Ymd',time());
$savepath = "static/".$basePath;
// 判断路径格式
if(empty($basePath)){
$array = array("error"=>1,"message"=>"路径解析错误");
self::message($array);
}
// 如果目录不存在就创建
if (!is_dir($savepath)){
$res = mkdir($savepath, 0755, true);
if(!$res){
$array = array("error"=>1,"message"=>"目录创建失败!");
self::message($array);
}
}
// 匹配文件内容
$file_content = base64_decode($post['img']);
// 生成图片文件名
$imgFileName = self::getFileName($savepath,$post['type']);
// 保存文件
if(!file_put_contents($savepath.'/'.$imgFileName ,$file_content)){
$array = array("error"=>1,"message"=>"图片保存失败");
self::message($array);
}
// 压缩信息
$imgResetSize_info = array("newpath"=>$savepath.'/'.$imgFileName, 'ext'=> $post['type']);
// 执行压缩
$status = self::imgResetSize($imgResetSize_info);
// 判断保存状态
if($status){ // 成功
// 返回信息
$array = array("error"=>0,"url"=>$this->serverHost.'/'.$basePath.'/'.$imgFileName);
self::message($array);
}else{ // 失败
// 删除文件
@unlink($savepath.'/'.$imgFileName);
// 返回信息
$array = array("error"=>1,"message"=>"图片处理失败!");
self::message($array);
}
}
/**
* 图片压缩 并 校验是否是正确的图片
* @access public
* @param array info 图片信息
* @param string info.newpath 图片路径
* @param string info.ext 图片格式
* @return Boolean 返回处理结果
*/
public function imgResetSize($info){
// 拼接地址
$image = new \Think\Image();
// 获取图像信息
$base_info = getimagesize($info['newpath']);
// 检测图像合法性
if(false === $base_info || (IMAGETYPE_GIF === $base_info[2] && empty($base_info['bits']))){
// 删除图片文件
// file_put_contents($info['newpath'], '');
@unlink($info['newpath']);
// 输出错误信息
$array = array("error"=>1,"message"=>"非法图像文件!");
self::message($array);
}
// 如果是GIF格式的图片 就直接跳过 不进行压缩
if($info['ext']=='gif'){
return true;
// 如果是png 因为怕是透明的 所以做特殊处理
}elseif($info['ext']=='png'){
//获取源图gd图像标识符
$srcImg = imagecreatefrompng($info['newpath']);
$srcWidth = imagesx($srcImg);
$srcHeight = imagesy($srcImg);
//创建新图
$newImg = imagecreatetruecolor($srcWidth, $srcHeight);
//分配颜色 + alpha,将颜色填充到新图上
$alpha = imagecolorallocatealpha($newImg, 0, 0, 0, 127);
imagefill($newImg, 0, 0, $alpha);
//将源图拷贝到新图上,并设置在保存 PNG 图像时保存完整的 alpha 通道信息
imagecopyresampled($newImg, $srcImg, 0, 0, 0, 0, $srcWidth, $srcHeight, $srcWidth, $srcHeight);
imagesavealpha($newImg, true);
return imagepng($newImg, $info['newpath']);
}
// 判断是否打开成功
if($image->open($info['newpath'])){
return $image->save($info['newpath'], $info['ext'], 85);
}else{
// 输出错误信息
$array = array("error"=>1,"message"=>"文件打开失败!");
self::message($array);
}
}
/**
* 输出信息函数
* @access public
* @param array $data 信息数组
* @return json
*/
public function message($data){
echo json_encode($data);
exit();
}
/**
* 生成文件名
* @access public
* @param string $savepath 保存路径
* @param type $type 图片类型
* @return string $imgFileName 文件名称
*/
public function getFileName($savepath,$type){
$imgFileName = mt_rand(0,9999999).'.'.$type;
if(file_exists($savepath.'/'.$imgFileName)){
return self::getFileName($savepath,$type);
}else{
return $imgFileName;
}
}
}
接口地址
文件上传方式
http://dgn.study.com/index.php/Home/Index/fileUpload.html
base64 方式
http://dgn.study.com/index.php/Home/Index/formUpload.html
接收方式 POST
必须参数
文件上传方式
POST.path 站点路径
FILES.imgFile 文件
base64 方式
POST.img 图片base64值
POST.type 图片类型
POST.webdir 站点路径
返回值类型 JSON
返回值
error 错误代码
1 有错误信息 失败
0 没有错误信息 成功
message 失败信息
只有失败才返回
url 图片路径
只有成功才返回