图片上传

manageApplicationFmall_cloudControllerProductController.class.php

//商品图片上传
public function upload_fileAction() {
        $public=D('public');
//上传图片的名称 $name='photo';
//上传图片的宽度
$width="700";
//上传图片的高度 $height
="300";
//检查上传图片的尺寸是否满足条件 $img_size
=$public->checkImgSize($width,$height,$name); if($img_size['status']==1){ $this->ajaxReturn(array('msg' =>'海景图片尺寸不对,应该为700*300','status' => 1)); } //判断上传图片的大小是否合适 if($_FILES[$name]['size'] > 3000000){ $this->ajaxReturn(array('msg' => '上传的图片不能超过3M','status' => 1)); } $picture_model = D('Picture'); //上传到图片站点服务器 $ask_result=$public->uploadImgToOnLine($name,3); if($ask_result['status']==1){ $this->ajaxReturn(array('msg' => $ask_result['msg'],'status' => 1)); } $image_size = getimagesize($ask_result['result']['fileview']);
/*******************************
print_r($image_size);
Array
(
    [0] => 1920
     [1] => 1200
     [2] => 2
     [3] => width="1920" height="1200"
     [bits] => 8
     [channels] => 3
     [mime] => image/jpeg
)
        /*******************************
//上传到本地
$localPath=$public->uploadImgToLocal($name,$ask_result['result']['fileName']);
if($localPath['status']==1){
$
this->ajaxReturn(array('msg' => $localPath['msg'],'status' => 1));
}

$product
= D('product'); //生成缩略图 $result = $product->uploadThumbImgToOnLine($name,$service_type,$source,true,$image_size,$localPath,$thumb_size); $data = array('msg' => '上传成功','status' => '0','img_url' => $ask_result['result']['filepath'],'filepath' => $ask_result['result']['fileview']); $this->ajaxReturn($data); }

manageApplicationFmall_cloudModelPublicModel.class.php

/*
 * @desc 本地生成缩略图后并将缩略图上传到远程服务器
 * @param $name 上传图片的名称
 * @param $service_type 上传图片到图片站点服务器的位置
 * @param $source 来源
 * @param $flag 是否生成缩略图
 * @param $image_size 原始图片的大小
 * @param $localPath 要生成缩略图的原始图片的路径
 * @param $thumb_size 要生成缩略图的尺寸
 */
public function uploadThumbImgToOnLine($name,$service_type,$source,$flag=false,$image_size=null,$localPath=null,$thumb_size=array()){
        //获取文件
        $fileName = $_FILES[$name];
        /************************************
        Array
        (
            [name] => 自然风光0084.jpg
            [type] => image/jpeg
            [tmp_name] => /tmp/phpxnpyyM
            [error] => 0
            [size] => 1076698
        )
        ************************************/
        //请选择你要上传得文件
        if(empty($fileName)){
            return array('status' => '1', 'msg' =>"请选择你要上传得文件");
        }
        //获取上传图片的名称
        $fileExtension = pathinfo($fileName['name']);
        /************************************
        Array
        (
            [dirname] => .
            [basename] => 自然风光0084.jpg
            [extension] => jpg
            [filename] => 自然风光0084
        )
        ************************************/
        //获取上传图片的后缀  jpg
        $ext = $fileExtension['extension'];
        //需要保存的文件名  96b6f15275899624240
        $receiveFile = substr(md5($fileName['tmp_name']) , 0, 5).time().rand(0, 9999);
        $filePath = $fileName['tmp_name'];  ///tmp/phpIeqArt
        //生成缩略图
        $min_size = $image_size[0] > $image_size[1] ?$image_size[1] : $image_size[0];
        /************************************
        print_r($image_size);
        Array
        (
            [0] => 1920
            [1] => 1200
            [2] => 2
            [3] => width="1920" height="1200"
            [bits] => 8
            [channels] => 3
            [mime] => image/jpeg
        )
         ************************************/
        if($flag){
            $image = new ThinkImage();
            //打开要生成缩略图的本地图片路径
            $image->open($localPath); //$localPath ---- /home/wwwroot/default/temp_img/6cc151527589502835.jpg
            $ask_path=substr($localPath,0,strrpos($localPath,'/'));// /home/wwwroot/default/temp_img
            foreach($thumb_size as $k=>$v){
                //生成缩略图
                $thumb_path=$ask_path."/".$receiveFile . '_'.$v['width'].'_'.$v['height'].'.' . $ext; ///home/wwwroot/default/temp_img/6e86415275905573730_400_400.jpg
                //复制图片并重命名
                copy($localPath, $thumb_path);
                //生成图片缩略图
                $image->thumb($v['width'], $v['height'], ThinkImage::IMAGE_THUMB_FILLED)->save($thumb_path, null, 100);
                $file_result=$this->upload($service_type,$source,$ext,$receiveFile,$filePath,$thumb_path);
            }
        }
        if(!$flag){
            $file_result=$this->upload($service_type,$source,$ext,$receiveFile,$filePath,$localPath);
        }
        $ask_result = json_decode($file_result,true);
        $ask_result['result']['fileName']=$receiveFile;
        return $ask_result;
}
//上传图片到图片站点服务器
public function upload($service_type,$source,$ext,$receiveFile,$localPath){
        //图片服务模型
        $picture_model = D('Picture');
        //将图片上传到图片站点服务器
        $ask_data = array('service_type' => $service_type,'ext'=>$ext,'receivename'=>$receiveFile ,'filePath' =>new CURLFile(realpath($localPath),'image/jpeg') );
        /************************************
        print_r($ask_data);
        Array
        (
            [service_type] => 3
            [ext] => jpg
            [receivename] => 7c4a2152759063527.jpg
            [filePath] => CURLFile Object
            (
                [name] => /tmp/phpUWHHys
                [mime] => image/jpeg
                [postname] =>
            )
        )
        ************************************/
        $file_result =$picture_model->dealParam($ask_data,$source);
        //删除本地的临时文件
        unlink($localPath);
        return $file_result;
}
 //图片上传到本地
 public function uploadImgToLocal($name,$receiveFile=null){
        $fileName=$_FILES[$name];
        $upload_path=C('temp_img'); //本地存储临时目录
        //验证目录
        if(!is_dir($upload_path)) { //若目录不存在则创建之
            mkdir($upload_path,0777,true);
        }
        //执行上传
        //读取文件流
        $streamData = file_get_contents($fileName['tmp_name']);
        if(empty($streamData)){
            return array('msg' => "文件已损坏",'status' => 1);
        }
        $fileExtension = pathinfo($fileName['name']);
        //文件后缀
        $ext = $fileExtension['extension'];
        if(empty($receiveFile)) {
            //需要保存的文件名
            $receiveFile = substr(md5($fileName['tmp_name']), 0, 5) . time() . rand(0, 9999) . '.' . $ext;
        }
        //写入文件流
        $ret = file_put_contents($upload_path.$receiveFile, $streamData, true);
        if(empty($ret)){
            return array('msg' => "写入文件流失败",'status' => 1);
        }
        return $upload_path.$receiveFile;
}
//图片上传尺寸校验
public function checkImgSize($width,$height,$name){
        $file=$_FILES[$name]['tmp_name'];
        //检查图片尺寸是否合法
        $image_size = getimagesize($file);
        $img_tmp_width=$image_size['0'];
        $img_tmp_height=$image_size['1'];
        if(empty($width) || empty($height) || empty($img_tmp_width) || empty($img_tmp_height)){
            $status = '1';
            $msg = "图片宽高不能为空!";
        }elseif($width<>$img_tmp_width ||  $height<>$img_tmp_height){
            $status = '1';
            $msg = '图片尺寸错误,正确值:'.$width.'px * '.$height.'px';
        }else{
            $status = '0';
            $msg = '验证通过';
        }
        $result = array('status'=>$status,'msg'=>$msg,'result'=>array('image_size'=>$image_size));
        return $result;
}

manageApplicationFmall_cloudModelPictureModel.class.php

<?php
/*
 * @title 中转图片上传服务
 * @author:依然范儿特西
 * @desc: 除中转图片服务得方法外,其他任何方法不要写在这里
 */
namespace Fmall_cloudModel;
use ThinkModel;
class PictureModel extends Model {
    Protected $autoCheckFields = false;    
    /**
     * @title 处理传参
     * @param $url 接口地址
     * @param $data 业务参数
     */
    public function dealParam($ask_data,$source){
        //接口地址
        $url=C("picture_img_domain")."/Home/upload/file_one";  
        $token=C("picture_token");
        $apiKey=C("picture_apikey");
        $timestamp=time();
        $version='v1.0';
        $source=$source;

        $file_name =  $ask_data['filePath'];   //文件不参与签名
        unset($ask_data['filePath']);
        $data=stripslashes(json_encode($ask_data));

        //签名
        $paramArr=array(
            'token'=>$token,
            'data'=>$data,
            'timestamp'=>$timestamp,
            'source'=>$source,
            'version'=>$version,
        );

        $sign = $this->sys_createSign($paramArr,$apiKey);
        $header = array("token:$token","timestamp:$timestamp","source:$source","version:$version","sign:$sign");   
        $result=$this->sys_tocurl($url,$header,$data,$file_name);
        return $result;
     }
    /**
     * @title 签名函数
     * @param $paramArr 系统参数
     * @param $apiKey apikey
     * @return string 返回签名
     */
    public function sys_createSign ($paramArr,$apiKey) {
         ksort($paramArr);
         $sign='';
         foreach ($paramArr as $key => $val) {
             if ($key != '' && $val != '') {
                 $sign .= $key."=".$val."&";
             }
         }
         $sign=rtrim($sign,"&");
         $sign .=$apiKey;
         $sign=strtolower($sign);
         $sign = md5($sign);
         return $sign;
     }
    /**
     * @title 远程调接口函数
     * @param $url 接口地址
     * @param $header 要传的头信息
     * @param $data 业务参数
     * @return string 返回签名
     */
    public function sys_tocurl($url,$header,$data,$file_name){
        $post_data = array("data"=>$data,'file_name'=>$file_name);
//初始化curl $ch
= curl_init(); //提交方式: post curl_setopt($ch, CURLOPT_POST, TRUE); //要求结果为字符串且输出到屏幕上 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //设置header curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); /* * 从可靠的角度,推荐指定CURL_SAFE_UPLOAD的值, * 明确告知php是容忍还是禁止旧的@语法。注意在低版本PHP中CURLOPT_SAFE_UPLOAD常量本身可能不存在,需要判断: */ if (class_exists('CURLFile')) { curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true); } else { if (defined('CURLOPT_SAFE_UPLOAD')) { curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false); } } //提交body 数据 curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); curl_setopt($ch, CURLOPT_URL, $url);
//运行curl $response
= curl_exec($ch); curl_close($ch); return $response; } }

manageApplicationCommonConfconfig.php

//图片服务api站点token 和密钥
'picture_img_domain'=>'http://img.fld8.cn/',
'picture_token'=>'5VMFrvTBQJPIZHs3IwKQrw==',
"picture_apikey"=>"e55305aef4c14093c8647b37230290af",
//图片上传到本地临时目录
'temp_img'=>'/home/wwwroot/default/temp_img/',

图片站点服务器源码

file-serverApplicationHomeControllerUploadController.class.php

<?php
namespace HomeController;
use ThinkController;
use ThinkModel;
class UploadController extends BaseController {   
    public function index(){
        $data = array('msg' =>"加载成功!" , 'status'=>'0','result'=>null);
        $this->ajaxReturn($data);
    }

    /*
     *  @desc 图片上传:单图
     *  @param service_type int 是 业务类型:
     *                      1 前台 - 用户头像
     *                      2 管理后台 - 广告图片
     *                      3 管理后台 - 商品图片
     *                      4 管理管理后台 - 商品详情
     *                      5 前台 - 打款凭证(大额订单)
     *                      6 管理后台 - icon图标
     *                      7 前台 - 店铺logo
     *                      8 管理后台 - APP开屏广告
     *                      9 店铺二维码 - 前台
* @author 依然范儿特西 *
/ public function file_one(){ $data = I("post.data"); $data = json_decode(htmlspecialchars_decode($data),true);//业务参数json格式 if(empty($data['service_type']) ){ //必传字段为空 $data = array('status' => '1','errorCode' => '300100', 'msg' =>"请选择业务类型",'result'=>null); $this->ajaxReturn($data); } if(empty($_FILES['file_name'])){//请选择你要上传得文件 $data = array('status' => '1','errorCode' => '300101', 'msg' =>"请选择你要上传得文件",'result'=>null); $this->ajaxReturn($data); } $ext = $data['ext']; $receivename = $data['receivename']; $service_type = $data['service_type']; $size_check = false; //是否开启尺寸验证 $file_type = array('jpg', 'gif', 'png', 'jpeg','tmp'); $file_maxSize = '5242880'; //5M $file_width = '100'; $file_height = '100'; switch ($service_type) { case '1': //用户头像 $folder_path ="/server/user/"; $file_maxSize = '13631488'; //13M break; case '2': //广告图片: 文件命名不能带有ad : 小米会屏蔽 $folder_path ="/server/billboard/";
break; case '3': //商品图片 $folder_path ="/server/goods/";
break; case '4': //商品详情 $folder_path ="/server/detail/";
break; case '5': //打款凭证(大额订单) $folder_path ="/server/large/"; $file_maxSize='13631488'; //13M break; case '6': //icon图标 $folder_path ="/server/icon/";
break; case '7': //店铺logo 前台 $folder_path ="/server/store/";
break; case '8': //APP开屏广告 $folder_path ="/server/peacock/";
break; case '9': //店铺二维码 $folder_path ="/server/qrcode/";
break; case '10': //商品分类 $folder_path ="/server/goodcate/";
break; case '11': //商品品牌 $folder_path ="/server/goodbrand/";
break; case '12': //提现附件 $folder_path ="/server/annexes/";
break; case '13': //富文本编辑器 $folder_path ="/server/text/";
break; default: $folder_path ='';
break; } $Upload_model = D('Upload'); $result = $Upload_model->upload_put_img('file_name',$size_check,$file_type,$file_maxSize,$file_width,$file_height,$folder_path,$service_type,$ext,$receivename); if($result['status'] == '1'){ $status = '1'; $errorCode = '300102'; $msg = $result['msg']; $result = null; }else{ $status = '0'; $errorCode = '0'; $msg = '操作成功!'; $result = array( 'filepath'=>$result['filepath'], 'fileview'=>$result['fileview'] ); } $return_data = array('status'=>$status,'errorCode'=>$errorCode,'msg'=>$msg,'result'=>$result); //写入请求日志 $this->api_log($return_data); $this->ajaxReturn($return_data); } }

file-serverApplicationHomeModelUploadModel.class.php

<?php
namespace HomeModel;
use ThinkModel;
/****
 * 图片上传
 */
class UploadModel extends Model
{
    Protected $autoCheckFields = false; 
   /*
    *  @desc 图片上传: 单图
    *  @author 依然范儿特西  
    *  @param file_name string 上传文件资源名称
    *  @param file_width int 规定得图片宽度
    *  @param file_height int 规定得图片高度 
    */
    public function upload_put_img($file_name,$size_check,$file_type,$file_maxSize,$file_width,$file_height,$folder_path,$service_type,$ext,$receivename) {
        $rootPath = C("upload_img_url");
        $upload_path = C('upload_path'); 

        if(empty($folder_path)){
            return $data = array('msg' => "文件夹路径不能为空",'status' => 1);   
        }
        //验证尺寸
        $fileName = $_FILES[$file_name];
        if($size_check){
            //检查图片尺寸是否合法
            $image_size = getimagesize($fileName['tmp_name']);
            $img_tmp_width=$image_size['0'];
            $img_tmp_height=$image_size['1'];
            $size_result = $this->checkImgSize($file_width,$file_height,$img_tmp_width,$img_tmp_height);
            if($size_result['status'] == '1'){
                return $size_result;   //格式错误直接返回
            }
        }
        //校验文件类型
        if(in_array($ext,$file_type) === false){
            return $data = array('msg' => "不允许的文件类型",'status' => 1); 
        }
        //验证大小
        if($fileName['size'] > $file_maxSize){
            return $data = array('msg' => "文件大小超出限制!",'status' => 1); 
        }
        
        //验证目录
        $returnPath = $upload_path.$folder_path.date("Ymd")."/";  //
        $root_save_dir_path = $rootPath.$returnPath;
        if(!is_dir($root_save_dir_path)) { //若目录不存在则创建之
            mkdir($root_save_dir_path,0777,true);
        }
        //执行上传  
        //读取文件流
        $streamData = file_get_contents($fileName['tmp_name']); 
        if(empty($streamData)){
            return $data = array('msg' => "文件已损坏",'status' => 1);
        }

        $save_file_path = $root_save_dir_path.$receivename;
        //写入文件流
        $ret = file_put_contents($save_file_path, $streamData, true); 
        //组装返回数据
        $finllay_path = $returnPath.$receivename;
        $finllay_view = C('img_base').$finllay_path;
        return  $data = array(
            'msg' => 'success',
            'status' => '0',
            'filepath' => $finllay_path,
            'fileview'=>$finllay_view
        );      
    }

/* * @desc 验证图片尺寸是否合法 * @author : 依然范儿特西 * @param img_tmp_width 上传图片宽 * @param img_tmp_height 上传图片高 * @param file_width 规定图片宽 * @param file_height 规定图片高 */ private function checkImgSize($file_width,$file_height,$img_tmp_width,$img_tmp_height){ if(empty($file_width) || empty($file_height) || empty($img_tmp_width) || empty($img_tmp_height)){ $status = '1'; $msg = "图片宽高不能为空!"; }elseif($file_width<>$img_tmp_width || $file_height<>$img_tmp_height){ $status = '1'; $msg = '图片尺寸错误,正确值:'.$file_width.'px * '.$file_height.'px'; }else{ $status = '0'; $msg = '验证通过'; } $result = array('status'=>$status,'msg'=>$msg); return $result; } }
原文地址:https://www.cnblogs.com/zouke1220/p/9105850.html