码迷,mamicode.com
首页 > Web开发 > 详细

php把 图片上传到 图片服务器

时间:2018-04-21 17:34:29      阅读:280      评论:0      收藏:0      [点我收藏+]

标签:error   ADG   field   rand   obj   false   成功路   错误   for   

图片服务器代码

<?php
/**
 * 图片服务器上传API接口
 * by Zx
 * date 2016-04-28
 */

header(‘Content-type:text/json‘);

//准备参数
$size = 10485760; //图片大小 单位字节
$type = array(‘image/jpeg‘, ‘image/gif‘, ‘image/png‘); //允许上传的图片类型

//验证数据完整性
if(isset($_FILES[‘imgs‘]) && isset($_POST[‘folder‘]))
{
    switch($_POST[‘folder‘])
    {
        case ‘goods_img‘:
            $path = ‘goods_img/‘.date(‘Y-m-d‘).‘/‘;
            break;
        case ‘goods_sku‘:
            $path = ‘goods_sku/‘.date(‘Y-m-d‘).‘/‘;
            break;
        default:
            $path = ‘default/‘.date(‘Y-m-d‘).‘/‘;
            break;
    }

    if (!is_dir($path))
    {
        //第三个参数是“true”表示能创建多级目录,iconv防止中文目录乱码
        mkdir(iconv("UTF-8", "GBK", $path),0777,true);
    }

    //开始图片上传
    $result = upload($path, $size, $type);

}else{
    //参数缺失
    $result = array(‘code‘ => 0, ‘msg‘ => ‘参数缺失‘);
}

echo json_encode($result);


/**
 * Upload 图片上传
 * @param $path 图片上传路径(一级目录)
 * @param $size 图片上传大小 单位字节
 * @param $type 允许上传的图片类型
 * @return array code(0==上传失败, 1==上传成功) path==上传成功路径 name==上传成功图片名称
 */
function upload($path, $size, $type){
    $file = $_FILES[‘imgs‘];

    if($file[‘error‘] > 0){
        switch($file[‘error‘]){
            case 1:
                return array(‘code‘ => 0, ‘msg‘ => ‘上传文件超过PHP配置文件中 upload_max_filesize的值‘);
                break;
            case 2:
                return array(‘code‘ => 0, ‘msg‘ => ‘上传文件超过PHP配置文件中 post_max_size的值‘);
                break;
            case 3:
                return array(‘code‘ => 0, ‘msg‘ => ‘上传失败,图片数据缺损‘);
                break;
            case 4:
                return array(‘code‘ => 0, ‘msg‘ => ‘没有文件被上传‘);
                break;
            case 6:
                return array(‘code‘ => 0, ‘msg‘ => ‘上传失败,找不到临时目录‘);
                break;
            default:
                return array(‘code‘ => 0, ‘msg‘ => ‘未知错误‘);
                break;
        }
    }

    if($file[‘size‘] > $size){
        return array(‘code‘ => 0, ‘msg‘ => ‘上传的图片大小超过限制的‘.$size.‘字节‘);
    }

    if(!in_array($file[‘type‘], $type)){
        return array(‘code‘ => 0, ‘msg‘ => ‘不是正确的图片类型‘);
    }

    $suffix = strrchr($file[‘name‘], ‘.‘);

    $newName = md5(time().uniqid().mt_rand(1,999)).$suffix;

    if(!file_exists($path)){
        mkdir($path);
    }

    $path = rtrim($path, ‘/‘);
    $p = $path.‘/‘.$newName;

    if(move_uploaded_file($file[‘tmp_name‘], $p)){
        return array(‘code‘ => 1, ‘msg‘ => ‘图片上传成功‘, ‘path‘ => $path, ‘name‘ => $newName);
    }else{
        return array(‘code‘ => 0, ‘msg‘ => ‘图片上传失败‘);
    }
}

 

前台代码

//上传商品图片
        $(‘#upload_goods_img‘).change(function(){
              //上传商品图片数量
              var small_goods_img_number = $(‘.small_number‘).length
              if(small_goods_img_number == 5){
                  error(‘最多上传五张图片‘);return;
              }

              $(‘#index‘).val(++small_goods_img_number);
              var formData = new FormData($( "#goods_img" )[0]);

            // var url = "{:U(‘UploadImg/uploadGoodsImg‘)}";
            var url = "{:U(‘UploadImg/upload_img‘)}";
            formData.append("img_name", "goods_img");
            formData.append("folder", "goods_img");
            formData.append("type", "goods_img");

            $.ajax({
                type:‘post‘,
                url:url,
                data:formData,
                cache: false,
                contentType: false,
                processData: false,
                success:function(data){

                    if(data.code){
                        //大图
                        var img_url = "{:C(‘IMG_SERVER_URL‘)}";
                        $(‘#upload_goods_img_big‘).attr(‘src‘, img_url+data.msg.goods_img_path);

                        //小图
                        addGoodsImgSmall(data.msg);
                    }else{
                        error(data.msg);
                    }
                }
            });
        });

 

php代码

/**
     * 上传图片到服务器
     * @return [type] [description]
     */
    public function upload_img()
    {
        if(IS_POST){
            $url = C(‘IMG_SERVER_URL‘).‘uploadImg.php‘; //图片API服务器
            $data = I(‘post.‘);
            $img_name = $data[‘img_name‘];
            if(!$img_name){
                $ajax[‘msg‘] = ‘File名称有误‘;
            }else{
                $tmpName = $_FILES[$img_name][‘name‘]; //上传上来的文件名
                $tmpFile = $_FILES[$img_name][‘tmp_name‘]; //上传上来的临时存储路径
                $tmpType = $_FILES[$img_name][‘type‘]; //上传上来的文件类型
                $folder = $data[‘folder‘]; //存储路径
                //执行上传
                $obj = json_decode(upload_file($url, $tmpName, $tmpFile, $tmpType, $folder));
                
                if($obj->code){
                    $path = $obj->path.‘/‘.$obj->name;

                    if($data[‘type‘] == ‘goods_img‘){ //商品图片

                        $model = D(‘GoodsImg‘);
                        $goods_img_data[‘img_path‘] = $path;
                        $goods_img_data[‘index‘] = I(‘index‘);
                        $goods_img_data[‘create_time‘] = time();
                        $goods_img_id = $model->add($goods_img_data);

                        if($goods_img_id){
                            $ajax[‘code‘] = ‘1‘;
                            $ajax[‘msg‘] = [
                                ‘id‘ => $goods_img_id,
                                ‘goods_img_path‘ => $path,
                            ];
                        }else{
                            $ajax[‘msg‘] = ‘上传失败‘;
                        }

                    }else if($data[‘type‘] == ‘goods_sku‘){ //商品SKU

                        $model = D(‘GoodsSku‘);
                        $goods_sku_img_data[‘sku_img_path‘] = $path;
                        $goods_sku_img_data[‘sku_distinguish‘] = $data[‘sku_distinguish‘];
                        $goods_sku_img_data[‘price‘] = $data[‘sku_price‘];
                        $goods_sku_img_data[‘create_time‘] = time();
                        $goods_sku_img_id = $model->add($goods_sku_img_data);
                        if($goods_sku_img_id){
                            $ajax[‘code‘] = ‘1‘;
                            $ajax[‘msg‘] = [
                                ‘id‘ => $goods_sku_img_id,
                                ‘goods_sku_img_path‘ => $path,
                                ‘sku_distinguish‘ => $data[‘sku_distinguish‘],
                                ‘price‘ => $data[‘sku_price‘]
                            ];
                        }else{
                            $ajax[‘msg‘] = ‘上传失败‘;
                        }
                    }

                }else{
                    $ajax[‘msg‘] = $obj->msg;
                }

            }
            $this->ajaxReturn($ajax);
        }
    }

上传文件curl

/** 
 * curl上传文件 
 *  
 * @param unknown $url 
 * @param unknown $filename 
 * @param unknown $path 
 * @param unknown $type 
 */  
function upload_file($url,$filename,$path,$type, $folder){  
    //php 5.5以上的用法  
    if (class_exists(‘\CURLFile‘)) {  
        $data = array(
            ‘imgs‘ => new \CURLFile(realpath($path),$type,$filename),
            ‘folder‘ => $folder
        );
    } else {  
        $data = array(  
            ‘imgs‘=>‘@‘.realpath($path).";type=".$type.";filename=".$filename,
            ‘folder‘ => $folder
        );  
    }
    $ch = curl_init();  
    curl_setopt($ch, CURLOPT_URL, $url);  
    curl_setopt($ch, CURLOPT_POST, true);  
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);  
    curl_setopt($ch, CURLOPT_HEADER, false);  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
    $return_data = curl_exec($ch);
    $return_data = trim($return_data);
    curl_close($ch);  
    return $return_data;  
}

 

php把 图片上传到 图片服务器

标签:error   ADG   field   rand   obj   false   成功路   错误   for   

原文地址:https://www.cnblogs.com/zjj1990/p/8901911.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!