天天看點

圖檔上傳到阿裡雲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/*" οnchange="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;
    }