> 백엔드 개발 > PHP 튜토리얼 > php怎么把图片上传到图片服务器

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

PHPz
풀어 주다: 2020-06-28 09:46:51
원래의
2155명이 탐색했습니다.

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

php怎么把图片上传到图片服务器?

图片服务器代码

<?php
/**
 * 图片服务器上传API接口
 * by Zx
 * date 2016-04-28
 */
header(&#39;Content-type:text/json&#39;);
//准备参数
$size = 10485760; //图片大小 单位字节
$type = array(&#39;image/jpeg&#39;, &#39;image/gif&#39;, &#39;image/png&#39;); //允许上传的图片类型
//验证数据完整性
if(isset($_FILES[&#39;imgs&#39;]) && isset($_POST[&#39;folder&#39;]))
{
    switch($_POST[&#39;folder&#39;])
    {
        case &#39;goods_img&#39;:
            $path = &#39;goods_img/&#39;.date(&#39;Y-m-d&#39;).&#39;/&#39;;
            break;
        case &#39;goods_sku&#39;:
            $path = &#39;goods_sku/&#39;.date(&#39;Y-m-d&#39;).&#39;/&#39;;
            break;
        default:
            $path = &#39;default/&#39;.date(&#39;Y-m-d&#39;).&#39;/&#39;;
            break;
    }
    if (!is_dir($path))
    {
        //第三个参数是“true”表示能创建多级目录,iconv防止中文目录乱码
        mkdir(iconv("UTF-8", "GBK", $path),0777,true);
    }
    //开始图片上传
    $result = upload($path, $size, $type);
}else{
    //参数缺失
    $result = array(&#39;code&#39; => 0, &#39;msg&#39; => &#39;参数缺失&#39;);
}
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[&#39;imgs&#39;];
    if($file[&#39;error&#39;] > 0){
        switch($file[&#39;error&#39;]){
            case 1:
                return array(&#39;code&#39; => 0, &#39;msg&#39; => &#39;上传文件超过PHP配置文件中 upload_max_filesize的值&#39;);
                break;
            case 2:
                return array(&#39;code&#39; => 0, &#39;msg&#39; => &#39;上传文件超过PHP配置文件中 post_max_size的值&#39;);
                break;
            case 3:
                return array(&#39;code&#39; => 0, &#39;msg&#39; => &#39;上传失败,图片数据缺损&#39;);
                break;
            case 4:
                return array(&#39;code&#39; => 0, &#39;msg&#39; => &#39;没有文件被上传&#39;);
                break;
            case 6:
                return array(&#39;code&#39; => 0, &#39;msg&#39; => &#39;上传失败,找不到临时目录&#39;);
                break;
            default:
                return array(&#39;code&#39; => 0, &#39;msg&#39; => &#39;未知错误&#39;);
                break;
        }
    }
    if($file[&#39;size&#39;] > $size){
        return array(&#39;code&#39; => 0, &#39;msg&#39; => &#39;上传的图片大小超过限制的&#39;.$size.&#39;字节&#39;);
    }
    if(!in_array($file[&#39;type&#39;], $type)){
        return array(&#39;code&#39; => 0, &#39;msg&#39; => &#39;不是正确的图片类型&#39;);
    }
    $suffix = strrchr($file[&#39;name&#39;], &#39;.&#39;);
    $newName = md5(time().uniqid().mt_rand(1,999)).$suffix;
    if(!file_exists($path)){
        mkdir($path);
    }
    $path = rtrim($path, &#39;/&#39;);
    $p = $path.&#39;/&#39;.$newName;
    if(move_uploaded_file($file[&#39;tmp_name&#39;], $p)){
        return array(&#39;code&#39; => 1, &#39;msg&#39; => &#39;图片上传成功&#39;, &#39;path&#39; => $path, &#39;name&#39; => $newName);
    }else{
        return array(&#39;code&#39; => 0, &#39;msg&#39; => &#39;图片上传失败&#39;);
    }
}
로그인 후 복사

前台代码

//上传商品图片
        $(&#39;#upload_goods_img&#39;).change(function(){
              //上传商品图片数量
              var small_goods_img_number = $(&#39;.small_number&#39;).length
              if(small_goods_img_number == 5){
                  error(&#39;最多上传五张图片&#39;);return;
              }
              $(&#39;#index&#39;).val(++small_goods_img_number);
              var formData = new FormData($( "#goods_img" )[0]);
            // var url = "{:U(&#39;UploadImg/uploadGoodsImg&#39;)}";
            var url = "{:U(&#39;UploadImg/upload_img&#39;)}";
            formData.append("img_name", "goods_img");
            formData.append("folder", "goods_img");
            formData.append("type", "goods_img");
            $.ajax({
                type:&#39;post&#39;,
                url:url,
                data:formData,
                cache: false,
                contentType: false,
                processData: false,
                success:function(data){
                    if(data.code){
                        //大图
                        var img_url = "{:C(&#39;IMG_SERVER_URL&#39;)}";
                        $(&#39;#upload_goods_img_big&#39;).attr(&#39;src&#39;, 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(&#39;IMG_SERVER_URL&#39;).&#39;uploadImg.php&#39;; //图片API服务器
            $data = I(&#39;post.&#39;);
            $img_name = $data[&#39;img_name&#39;];
            if(!$img_name){
                $ajax[&#39;msg&#39;] = &#39;File名称有误&#39;;
            }else{
                $tmpName = $_FILES[$img_name][&#39;name&#39;]; //上传上来的文件名
                $tmpFile = $_FILES[$img_name][&#39;tmp_name&#39;]; //上传上来的临时存储路径
                $tmpType = $_FILES[$img_name][&#39;type&#39;]; //上传上来的文件类型
                $folder = $data[&#39;folder&#39;]; //存储路径
                //执行上传
                $obj = json_decode(upload_file($url, $tmpName, $tmpFile, $tmpType, $folder));
                
                if($obj->code){
                    $path = $obj->path.&#39;/&#39;.$obj->name;
                    if($data[&#39;type&#39;] == &#39;goods_img&#39;){ //商品图片
                        $model = D(&#39;GoodsImg&#39;);
                        $goods_img_data[&#39;img_path&#39;] = $path;
                        $goods_img_data[&#39;index&#39;] = I(&#39;index&#39;);
                        $goods_img_data[&#39;create_time&#39;] = time();
                        $goods_img_id = $model->add($goods_img_data);
                        if($goods_img_id){
                            $ajax[&#39;code&#39;] = &#39;1&#39;;
                            $ajax[&#39;msg&#39;] = [
                                &#39;id&#39; => $goods_img_id,
                                &#39;goods_img_path&#39; => $path,
                            ];
                        }else{
                            $ajax[&#39;msg&#39;] = &#39;上传失败&#39;;
                        }
                    }else if($data[&#39;type&#39;] == &#39;goods_sku&#39;){ //商品SKU
                        $model = D(&#39;GoodsSku&#39;);
                        $goods_sku_img_data[&#39;sku_img_path&#39;] = $path;
                        $goods_sku_img_data[&#39;sku_distinguish&#39;] = $data[&#39;sku_distinguish&#39;];
                        $goods_sku_img_data[&#39;price&#39;] = $data[&#39;sku_price&#39;];
                        $goods_sku_img_data[&#39;create_time&#39;] = time();
                        $goods_sku_img_id = $model->add($goods_sku_img_data);
                        if($goods_sku_img_id){
                            $ajax[&#39;code&#39;] = &#39;1&#39;;
                            $ajax[&#39;msg&#39;] = [
                                &#39;id&#39; => $goods_sku_img_id,
                                &#39;goods_sku_img_path&#39; => $path,
                                &#39;sku_distinguish&#39; => $data[&#39;sku_distinguish&#39;],
                                &#39;price&#39; => $data[&#39;sku_price&#39;]
                            ];
                        }else{
                            $ajax[&#39;msg&#39;] = &#39;上传失败&#39;;
                        }
                    }
                }else{
                    $ajax[&#39;msg&#39;] = $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(&#39;\CURLFile&#39;)) {  
        $data = array(
            &#39;imgs&#39; => new \CURLFile(realpath($path),$type,$filename),
            &#39;folder&#39; => $folder
        );
    } else {  
        $data = array(  
            &#39;imgs&#39;=>&#39;@&#39;.realpath($path).";type=".$type.";filename=".$filename,
            &#39;folder&#39; => $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中文网

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿