图片上传到阿里云oss保存

互联网新时代除了纯信息展示类的网站基本都是有文件上传功能的但是随着业务的发展如果上传的文件和数据库都和网站程序源代码放在一起那是有相当多的弊端的

1用户体验比较差,

2:服务器的成本略高

3:静态文件会占用大量带宽

常规的做法是把源代码放到一台服务器上图片等静态文件放在另一台服务器上

当一个神奇的时代的到来后一切就变的更加简单了在业务还比较小的时候我们无需大费周折的去搞一台静态文件服务器直接使用第三方的即可


如果对阿里云OSS有什么问题的可以自行查看 https://help.aliyun.com/document_detail/31817.html?spm=a2c4g.11186623.6.539.cB4wo2




下面简单介绍一下本地图片上传到阿里云OSS的两种方法


1.直接上传不保存到本地

测试页面直接用form表单提交,后台接收并上传,这样做由于form表单限制文件大小,而且不能对文件进行操作不是很好,不多介绍了


2.图片文件转成base64格式,接收并保存上传,


<div class="imgWrap">
                        <img id="objImg" class="showImg">
                        <input type="file" accept="image/*" onchange="selectFileImage(this, false, 2, '1')" data="1" class="jsImg">
                        <div class="logo_up">
                            <i></i>
                            <span>添加图片</span>
                        </div>
                        <div class="jdtUP dn " style="left: 0px; top: 0px; width: 100%; height: 100%; border-radius: 100%;">
                            <div>
                                <img src="/Public/static/img/wait_proc.png" style="width: auto;">
                            </div>
                            <div>
                                <span>上传中...</span>
                            </div>
                        </div>
                    </div>
js处理:

function selectFileImage(fileObj, isupLoad, sign, myCardId, listIndex) {
    var file = fileObj.files['0'];
    console.log("file.size",file )
    //图片方向角 added by lzk  
    var Orientation = null;
    if (!file) {
        $(".jdtUP").hide();
        return false;
    }
    var fileSize = Math.round(file.size / 1024 / 1024);
    if (file) {
        console.log("正在上传,请稍后...");
        var rFilter = /^(image\/jpeg|image\/png)$/i; // 检查图片格式  
        if (!rFilter.test(file.type)) {
            //showMyTips("请选择jpeg、png格式的图片", false);  
            return;
        }
        //获取照片方向角属性,用户旋转控制  
        EXIF.getData(file, function () {
            // alert(EXIF.pretty(this));  
            EXIF.getAllTags(this);
            //alert(EXIF.getTag(this, 'Orientation'));   
            Orientation = EXIF.getTag(this, 'Orientation');
            //return;  
        });
        var oReader = new FileReader();
        oReader.onload = function (e) {
            var image = new Image();
            image.src = e.target.result;
            image.onload = function () {
                var expectWidth = this.naturalWidth;
                var expectHeight = this.naturalHeight;
                if (this.naturalWidth > 800) {
                    expectWidth = 800;
                    expectHeight = expectWidth * this.naturalHeight / this.naturalWidth;
                } else if (this.naturalHeight > 1200) {
                    expectHeight = 1200;
                    expectWidth = expectHeight * this.naturalWidth / this.naturalHeight;
                }
                var canvas = document.createElement("canvas");
                var ctx = canvas.getContext("2d");
                canvas.width = expectWidth;
                canvas.height = expectHeight;
                ctx.clearRect(0, 0, canvas.width, canvas.width);
                ctx.drawImage(this, 0, 0, expectWidth, expectHeight);
                var base64 = null;
                //修复ios  
                if (navigator.userAgent.match(/iphone/i)) {
                    console.log('iphone');
                    //alert(expectWidth + ',' + expectHeight);  
                    //如果方向角不为1,都需要进行旋转 added by lzk  
                    if (Orientation != "" && Orientation != 1) {
                        // alert('旋转处理');  
                        switch (Orientation) {
                            case 6://需要顺时针(向左)90度旋转  
                                // alert('需要顺时针(向左)90度旋转');
                                rotateImg(this, 'left', canvas, canvas.width, canvas.height);
                                break;
                            case 8://需要逆时针(向右)90度旋转  
                                // alert('需要顺时针(向右)90度旋转');
                                rotateImg(this, 'right', canvas, canvas.width, canvas.height);
                                break;
                            case 3://需要180度旋转  
                                // alert('需要180度旋转');
                                rotateImg(this, 'right', canvas, canvas.width, canvas.height);//转两次  
                                rotateImg(this, 'right', canvas, canvas.width, canvas.height);
                                break;
                        }
                    }
                    // 设置压缩比例
                    var compressRate = getCompressRate(1, fileSize);
                    console.log(compressRate)
                    base64 = canvas.toDataURL("image/jpeg", compressRate);
                } else if (navigator.userAgent.match(/Android/i)) {// 修复android  
                    // var encoder = new JPEGEncoder();
                    // alert('安卓');
                    var compressRate = getCompressRate(1, fileSize);
                    base64 = canvas.toDataURL("image/jpeg", compressRate);
                } else {
                    //alert(Orientation);  
                    if (Orientation != "" && Orientation != 1) {
                        //alert('旋转处理');  
                        switch (Orientation) {
                            case 6://需要顺时针(向左)90度旋转  
                                // alert('需要顺时针(向左)90度旋转');  
                                rotateImg(this, 'left', canvas, canvas.width, canvas.height);
                                break;
                            case 8://需要逆时针(向右)90度旋转  
                                // alert('需要顺时针(向右)90度旋转');  
                                rotateImg(this, 'right', canvas, canvas.width, canvas.height);
                                break;
                            case 3://需要180度旋转  
                                // alert('需要180度旋转');  
                                rotateImg(this, 'right', canvas, canvas.width, canvas.height);//转两次  
                                rotateImg(this, 'right', canvas, canvas.width, canvas.widheightth);
                                break;
                        }
                    }
                    var compressRate = getCompressRate(1, fileSize);
                    base64 = canvas.toDataURL("image/jpeg", compressRate);
                }
                $("#hidpic").val(base64);
                if (isupLoad) {
                    console.log("zhingxin")
                    post(base64, sign, myCardId);
                } else {
                    $(".jdtUP").hide();
                }
            };
        };
        oReader.readAsDataURL(file);
    }
}
//对图片旋转处理 added by lzk  
function rotateImg(img, direction, canvas, w, h) {
    //alert(img);  
    //最小与最大旋转方向,图片旋转4次后回到原方向    
    var min_step = 0;
    var max_step = 3;
    //var img = document.getElementById(pid);    
    if (img == null)
        return;
    //img的高度和宽度不能在img元素隐藏后获取,否则会出错    
    var height = h;
    var width = w;
    //var step = img.getAttribute('step');    
    var step = 2;
    if (step == null) {
        step = min_step;
    }
    if (direction == 'right') {
        step++;
        //旋转到原位置,即超过最大值    
        step > max_step && (step = min_step);
    } else {
        step--;
        step < min_step && (step = max_step);
    }
    //旋转角度以弧度值为参数    
    var degree = step * 90 * Math.PI / 180;
    var ctx = canvas.getContext('2d');
    switch (step) {
        case 0:
            canvas.width = width;
            canvas.height = height;
            ctx.drawImage(img, 0, 0, w, h);
            break;
        case 1:
            canvas.width = height;
            canvas.height = width;
            ctx.rotate(degree);
            ctx.drawImage(img, 0, -height, w, h);
            break;
        case 2:
            canvas.width = width;
            canvas.height = height;
            ctx.rotate(degree);
            ctx.drawImage(img, -width, -height, w, h);
            break;
        case 3:
            canvas.width = height;
            canvas.height = width;
            ctx.rotate(degree);
            ctx.drawImage(img, -width, 0, w, h);
            break;
    }
}
//计算压缩比率,size单位为MB
function getCompressRate(allowMaxSize, fileSize) {
    var compressRate = 1;
    if (fileSize / allowMaxSize > 10) {
        compressRate = 0.5;
    } else if (fileSize / allowMaxSize > 5) {
        compressRate = 0.6;
    } else if (fileSize / allowMaxSize > 3) {
        compressRate = 0.7;
    } else if (fileSize > allowMaxSize) {
        compressRate = 0.8;
    } else {
        compressRate = 0.9;
    }
    return compressRate;
}

// 上传路径
function post(new_img_up) {
    var url = "";//后台地址
        url = "{:U('Customer/uploadCardPost')}";
        $.post(url, {'new_img_up': new_img_up}, function (data) {
            if (data.status == 200) {
                if (data.url) {
                    toast("图片上传成功");
                    $(".jdtUP").hide();
                }
            } else {
                $(".jdtUP").hide();
                alert(data.msg);
            }
        });
    
}

后台处理:
 /**
     * 图片上传
     */
    public function uploads($base64_img) {
        if ($base64_img == '') {
            $data['msg'] = '图片路径为空';
            $data['status'] = 1002;
            return $data;
        }
        $up_dir = '.' . C('UPLOAD_DIR'); //存放在当前目录的upload文件夹下
        if (!file_exists($up_dir)) {
            mkdir($up_dir, 0777);
        }
        $up_dir_son = $up_dir . date('Y-m-d') . '/';
        if (!file_exists($up_dir_son)) {
            mkdir($up_dir_son, 0777);
        }
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)) {
            $type = $result[2];
            $file_name = $this->getName();
            if (in_array($type, array('pjpeg', 'jpeg', 'jpg', 'gif', 'bmp', 'png'))) {
                $new_file = $up_dir_son . $file_name . '.' . $type;
                if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_img)))) {
                    $img_path = str_replace('../../..', '', $new_file);
                    $img_path = substr($img_path, 1);
                    //保存图片到阿里云oss
                    if ($_SESSION['wechat_member_id'] == 1) {
                        $oss_img = $this->aliyun($img_path, $type);
                        $data['oss_img'] = $oss_img;//成功之后可以删除本地文件
                    }
                    $data['img_path'] = $img_path;
                    $data['msg'] = '图片上传成功';
                    $data['status'] = 200;
                    return $data;
                } else {
                    $data['msg'] = '图片上传失败';
                    $data['status'] = 1007;
                    return $data;
                }
            } else {
                $data['msg'] = '图片上传类型错误';
                $data['status'] = 1008;
                return $data;
            }
        } else {
            $data['msg'] = '文件错误';
            $data['status'] = 1009;
            return $data;
        }
    }

阿里云oss上传代码 sdk请自行下载,寻找自己合适的版本 https://help.aliyun.com/document_detail/32099.html?spm=a2c4g.11186623.6.778.H08z1z


 /**
     * 
     * 阿里云OSS图片上传
     */
    public function aliyun($info = '', $type = 'jpg', $way = 'oss要保存的文件目录', $bucket = 'oss创建项目名称') {
        $accessKeyId = ''; //去阿里云后台获取秘钥
        $accessKeySecret = ''; //去阿里云后台获取秘钥
        $endpoint = ''; //你的阿里云OSS地址
        $ossClient = new \OSS\OssClient($accessKeyId, $accessKeySecret, $endpoint);
//        判断bucketname是否存在,不存在就去创建
        if (!$ossClient->doesBucketExist($bucket)) {
            $ossClient->createBucket($bucket);
        }
        //想要保存文件的名称
        $file_name = $this->getName();
        $object = $way . date('Y-m-d') . '/' . $file_name . '.' . $type;
        $file = '.' . $info; //文件路径,必须是本地的
        try {
            $ossClient->uploadFile($bucket, $object, $file);
        } catch (OssException $e) {
            $e->getErrorMessage();
        }
        return $object;
    }

    //文件命名
    public function getName() {
        $rand_number = rand(10000, 99999);
        $file_name = date('His') . $rand_number;
        return $file_name;
    }


猜你喜欢

转载自blog.csdn.net/qq_35349114/article/details/79579604