七牛云存储搭建图床

来源:互联网 发布:江宁区广电网络营业厅 编辑:程序博客网 时间:2024/06/10 04:11

//////////////////////2016/10/29/////////////////////

/////////////////////by   xbw//////////////////////////


用了七牛云一段时间,感觉真心不错,免费的足够用了,为了修改域名充值了10元,其实无所谓,

现在想想嵌入程序中管他链接长短,反正不用手动输入,所以绑定不绑定域名都无所谓。

上传下载速度都很快,我个人很少用在博客上,搭建了一个app的广告投放平台,

利用七牛云搭建图床再好不过了。


按着七牛云API一步步来。

我选择了php sdk 还用了点 js sdk


autoload.php

<?phpfunction classLoader($class){    $path = str_replace('\\', DIRECTORY_SEPARATOR, $class);    $file = __DIR__ . '/src/' . $path . '.php';    if (file_exists($file)) {        require_once $file;    }}spl_autoload_register('classLoader');require_once  __DIR__ . '/src/Qiniu/functions.php';

token.php

<?phprequire_once __DIR__ . '/../autoload.php';use Qiniu\Auth;$accessKey = '七牛云账号管理获取';$secretKey = '七牛云账号管理获取';$auth = new Auth($accessKey, $secretKey);$bucket = '存储空间名字,不是域名';$upToken = $auth->uploadToken($bucket);    $rs['uptoken']=$upToken;    //看需要什么数据格式,json或者单纯字符串    //echo json_encode($rs);    echo $upToken;

每次上传图片都需要先获取这个token,这个token也作为post参数。

广告平台界面

<?php require("../token/config.php"); ?><!doctype html><html lang="en"><head>    <meta charset="UTF-8">    <title>广告平台</title>    <link href="images/favicon.ico" rel="shortcut icon">    <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css">    <link rel="stylesheet" href="styles/main.css">    <link rel="stylesheet" href="styles/highlight.css">    <script type="text/javascript" src="bower_components/jquery/jquery.min.js"></script>    <!--[if lt IE 9]>      <script src="bower_components/respond/dest/respond.min.js"></script>    <![endif]--></head><body>    <nav class="navbar navbar-default navbar-fixed-top">      <div class="container">        <div class="navbar-header">          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-6" aria-expanded="false">            <span class="sr-only">Toggle navigation</span>            <span class="icon-bar"></span>            <span class="icon-bar"></span>            <span class="icon-bar"></span>          </button>          <a class="navbar-brand" href="#">冰糖图床</a>        </div>        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-6">          <ul class="nav navbar-nav">            <li class="active"><a href="#">首页</a></li>          </ul>        </div>      </div>    </nav>    <div class="container" style="padding-top: 60px;">        <ul class="nav nav-tabs" role="tablist">            <li role="presentation" class="active">                <a href="#demo" id="demo-tab" role="tab" data-toggle="tab" aria-controls="demo" aria-expanded="true">广告</a>            </li>        </ul>        <div class="tab-content">            <div role="tabpanel" class="tab-pane fade in active" id="demo" aria-labelledby="demo-tab">                <div class="row" style="margin-top: 20px;">                    <input type="hidden" id="domain" value="<?php echo $domain; ?>">                    <input type="hidden" id="uptoken_url" value="<?php echo $uptoken_url; ?>">                    <ul class="tip col-md-12 text-mute">                                            <li>                            <small>临时上传的空间不定时清空,请勿保存重要文件。</small>                        </li>                        <li>                            <small>Html5模式大于4M文件采用分块上传。</small>                        </li>                        <li>                            <small>上传图片可查看处理效果。</small>                        </li>                        <li>                            <small>本示例限制最大上传文件100M。</small>                        </li>                    </ul>                    <div class="col-md-12">                        <div id="container">                            <a class="btn btn-default btn-lg " id="pickfiles" href="#" >                                <i class="glyphicon glyphicon-plus"></i>                                <span>选择文件</span>                            </a>                        </div>                    </div>                    <div style="display:none" id="success" class="col-md-12">                        <div class="alert-success">                            队列全部文件处理完毕                        </div>                    </div>                    <div class="col-md-12 ">                        <table class="table table-striped table-hover text-left"   style="margin-top:40px;display:none">                            <thead>                              <tr>                                <th class="col-md-4">文件名</th>                                <th class="col-md-2">大小</th>                                <th class="col-md-4">细节</th>                                <th class="col-md-2">广告</th>                              </tr>                            </thead>                            <tbody id="fsUploadProgress">                            </tbody>                        </table>                    </div>                </div>            </div>        </div>    </div><script>function displayHideUI(){    var ui =document.getElementById("upup");    ui.style.display="none";}                  function uploadxu(){                    $.ajax({                         type:"GET",                         url:"../../mvp/ad/adsplash.php",                         dataType:"json",                         data:{                         url: $('#uurl').val(),                         type: $('#select option:selected') .val()                         },                         success:function(data){                           alert($('#select option:selected') .val()+"上传成功");                           displayHideUI();                           console.log("zhengque");                         },                         error:function(jqXHR){                           alert($('#select option:selected') .val()+"上传失败");                         // 在控制台输出错误信息                         console.log("cuowu");                         }                         });                  }</script><script type="text/javascript" src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script><script type="text/javascript" src="bower_components/plupload/js/moxie.js"></script><script type="text/javascript" src="bower_components/plupload/js/plupload.dev.js"></script><!-- <script type="text/javascript" src="bower_components/plupload/js/plupload.full.min.js"></script> --><script type="text/javascript" src="bower_components/plupload/js/i18n/zh_CN.js"></script><script type="text/javascript" src="scripts/ui.js"></script><script type="text/javascript" src="src/qiniu.js"></script><script type="text/javascript" src="scripts/highlight.js"></script><script type="text/javascript" src="scripts/main.js"></script><script type="text/javascript">hljs.initHighlightingOnLoad();</script></body></html>
修改ui.js以适应上传图片之后的广告投放操作

/*global plupload *//*global qiniu */function FileProgress(file, targetID) {    this.fileProgressID = file.id;    this.file = file;    this.opacity = 100;    this.height = 0;    this.fileProgressWrapper = $('#' + this.fileProgressID);    if (!this.fileProgressWrapper.length) {        // <div class="progress">        //   <div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100" style="width: 20%">        //     <span class="sr-only">20% Complete</span>        //   </div>        // </div>        this.fileProgressWrapper = $('<tr></tr>');        var Wrappeer = this.fileProgressWrapper;        Wrappeer.attr('id', this.fileProgressID).addClass('progressContainer');        var progressText = $("<td/>");        progressText.addClass('progressName').text(file.name);        var fileSize = plupload.formatSize(file.size).toUpperCase();        var progressSize = $("<td/>");        progressSize.addClass("progressFileSize").text(fileSize);        var progressBarTd = $("<td/>");        //progressBarTd.addClass('ad').text('ad');                        var progressBarBox = $("<div/>");        progressBarBox.addClass('info');        var progressBarWrapper = $("<div/>");        progressBarWrapper.addClass("progress progress-striped");        var progressBar = $("<div/>");        progressBar.addClass("progress-bar progress-bar-info")            .attr('role', 'progressbar')            .attr('aria-valuemax', 100)            .attr('aria-valuenow', 0)            .attr('aria-valuein', 0)            .width('0%');        var progressBarPercent = $('<span class=sr-only />');        progressBarPercent.text(fileSize);        var progressCancel = $('<a href=javascript:; />');        progressCancel.show().addClass('progressCancel').text('×');        progressBar.append(progressBarPercent);        progressBarWrapper.append(progressBar);        progressBarBox.append(progressBarWrapper);        progressBarBox.append(progressCancel);        var progressBarStatus = $('<div class="status text-center"/>');        progressBarBox.append(progressBarStatus);        progressBarTd.append(progressBarBox);        //2016/10/25许博文修改        var progressAd =$("<td/>");        progressAd.append("<select id='select'><option value='A'>开屏页</option><option value='B1'>广告A</option><option value='B2'>广告B</option><option value='B3'>广告C</option><option value='B4'>广告D</option></select><br><br><br><button id='upup' onclick='uploadxu()' style='display:block;'>确定</button>");                Wrappeer.append(progressText);        Wrappeer.append(progressSize);        Wrappeer.append(progressBarTd);        Wrappeer.append(progressAd);        $('#' + targetID).append(Wrappeer);    } else {        this.reset();    }    this.height = this.fileProgressWrapper.offset().top;    this.setTimer(null);}FileProgress.prototype.setTimer = function(timer) {    this.fileProgressWrapper.FP_TIMER = timer;};FileProgress.prototype.getTimer = function(timer) {    return this.fileProgressWrapper.FP_TIMER || null;};FileProgress.prototype.reset = function() {    this.fileProgressWrapper.attr('class', "progressContainer");    this.fileProgressWrapper.find('td .progress .progress-bar-info').attr('aria-valuenow', 0).width('0%').find('span').text('');    this.appear();};FileProgress.prototype.setChunkProgess = function(chunk_size) {    var chunk_amount = Math.ceil(this.file.size / chunk_size);    if (chunk_amount === 1) {        return false;    }    var viewProgess = $('<button class="btn btn-default">查看分块上传进度</button>');    var progressBarChunkTr = $('<tr class="chunk-status-tr"><td colspan=3></td></tr>');    var progressBarChunk = $('<div/>');    for (var i = 1; i <= chunk_amount; i++) {        var col = $('<div class="col-md-2"/>');        var progressBarWrapper = $('<div class="progress progress-striped"></div');        var progressBar = $("<div/>");        progressBar.addClass("progress-bar progress-bar-info text-left")            .attr('role', 'progressbar')            .attr('aria-valuemax', 100)            .attr('aria-valuenow', 0)            .attr('aria-valuein', 0)            .width('0%')            .attr('id', this.file.id + '_' + i)            .text('');        var progressBarStatus = $('<span/>');        progressBarStatus.addClass('chunk-status').text();        progressBarWrapper.append(progressBar);        progressBarWrapper.append(progressBarStatus);        col.append(progressBarWrapper);        progressBarChunk.append(col);    }    if(!this.fileProgressWrapper.find('td:eq(2) .btn-default').length){        this.fileProgressWrapper.find('td>div').append(viewProgess);    }    progressBarChunkTr.hide().find('td').append(progressBarChunk);    progressBarChunkTr.insertAfter(this.fileProgressWrapper);};FileProgress.prototype.setProgress = function(percentage, speed, chunk_size) {    this.fileProgressWrapper.attr('class', "progressContainer green");    var file = this.file;    var uploaded = file.loaded;    var size = plupload.formatSize(uploaded).toUpperCase();    var formatSpeed = plupload.formatSize(speed).toUpperCase();    var progressbar = this.fileProgressWrapper.find('td .progress').find('.progress-bar-info');    if (this.fileProgressWrapper.find('.status').text() === '取消上传'){        return;    }    this.fileProgressWrapper.find('.status').text("已上传: " + size + " 上传速度: " + formatSpeed + "/s");    percentage = parseInt(percentage, 10);    if (file.status !== plupload.DONE && percentage === 100) {        percentage = 99;    }    progressbar.attr('aria-valuenow', percentage).css('width', percentage + '%');    if (chunk_size) {        var chunk_amount = Math.ceil(file.size / chunk_size);        if (chunk_amount === 1) {            return false;        }        var current_uploading_chunk = Math.ceil(uploaded / chunk_size);        var pre_chunk, text;        for (var index = 0; index < current_uploading_chunk; index++) {            pre_chunk = $('#' + file.id + "_" + index);            pre_chunk.width('100%').removeClass().addClass('alert-success').attr('aria-valuenow', 100);            text = "块" + index + "上传进度100%";            pre_chunk.next().html(text);        }        var currentProgessBar = $('#' + file.id + "_" + current_uploading_chunk);        var current_chunk_percent;        if (current_uploading_chunk < chunk_amount) {            if (uploaded % chunk_size) {                current_chunk_percent = ((uploaded % chunk_size) / chunk_size * 100).toFixed(2);            } else {                current_chunk_percent = 100;                currentProgessBar.removeClass().addClass('alert-success');            }        } else {            var last_chunk_size = file.size - chunk_size * (chunk_amount - 1);            var left_file_size = file.size - uploaded;            if (left_file_size % last_chunk_size) {                current_chunk_percent = ((uploaded % chunk_size) / last_chunk_size * 100).toFixed(2);            } else {                current_chunk_percent = 100;                currentProgessBar.removeClass().addClass('alert-success');            }        }        currentProgessBar.width(current_chunk_percent + '%');        currentProgessBar.attr('aria-valuenow', current_chunk_percent);        text = "块" + current_uploading_chunk + "上传进度" + current_chunk_percent + '%';        currentProgessBar.next().html(text);    }    this.appear();};FileProgress.prototype.setComplete = function(up, info) {    var td = this.fileProgressWrapper.find('td:eq(2)'),        tdProgress = td.find('.progress');    var res = $.parseJSON(info);    var url;    if (res.url) {        url = res.url;        str = "<div><strong>Link:</strong><a href=" + res.url + " target='_blank' > " + res.url + "</a></div>" +        "<div class=hash><strong>Hash:</strong>" + res.hash + "</div> <input type='hidden' id='uurl' name='uurl' value=" + res.url + " />";    } else {        var domain = up.getOption('domain');        url = domain + encodeURI(res.key);        var link = domain + res.key;        str = "<div><strong>Link:</strong><a href=" + url + " target='_blank' > " + link + "</a></div>" +        "<div class=hash><strong>Hash:</strong>" + res.hash + "</div> <input type='hidden' id='uurl' name='uurl' value=" + url + " />";    }    tdProgress.html(str).removeClass().next().next('.status').hide();    td.find('.progressCancel').hide();    var progressNameTd = this.fileProgressWrapper.find('.progressName');    var imageView = '?imageView2/1/w/100/h/100';    var isImage = function(url) {        var res, suffix = "";        var imageSuffixes = ["png", "jpg", "jpeg", "gif", "bmp"];        var suffixMatch = /\.([a-zA-Z0-9]+)(\?|\@|$)/;        if (!url || !suffixMatch.test(url)) {            return false;        }        res = suffixMatch.exec(url);        suffix = res[1].toLowerCase();        for (var i = 0, l = imageSuffixes.length; i < l; i++) {            if (suffix === imageSuffixes[i]) {                return true;            }        }        return false;    };    var isImg = isImage(url);    var Wrapper = $('<div class="Wrapper"/>');    var imgWrapper = $('<div class="imgWrapper col-md-3"/>');    var linkWrapper = $('<a class="linkWrapper" target="_blank"/>');    var showImg = $('<img src="images/loading.gif"/>');    progressNameTd.append(Wrapper);    if (!isImg) {        showImg.attr('src', 'images/default.png');        Wrapper.addClass('default');        imgWrapper.append(showImg);        Wrapper.append(imgWrapper);    } else {        linkWrapper.append(showImg);        imgWrapper.append(linkWrapper);        Wrapper.append(imgWrapper);        var img = new Image();        if (!/imageView/.test(url)) {            url += imageView        }        $(img).attr('src', url);        var height_space = 340;        $(img).on('load', function() {            showImg.attr('src', url);            linkWrapper.attr('href', url).attr('title', '查看原图');            function initImg(url, key, height) {                $('#myModal-img').modal();                var modalBody = $('#myModal-img').find('.modal-body');                if (height <= 300) {                    $('#myModal-img').find('.text-warning').show();                }                var newImg = new Image();                modalBody.find('img').attr('src', 'images/loading.gif');                newImg.onload = function() {                    modalBody.find('img').attr('src', url).data('key', key).data('h', height);                    modalBody.find('.modal-body-wrapper').find('a').attr('href', url);                };                newImg.src = url;            }            var infoWrapper = $('<div class="infoWrapper col-md-6"></div>');            var fopLink = $('<a class="fopLink"/>');            fopLink.attr('data-key', res.key).text('查看处理效果');            infoWrapper.append(fopLink);            fopLink.on('click', function() {                var key = $(this).data('key');                var height = parseInt($(this).parents('.Wrapper').find('.origin-height').text(), 10);                if (height > $(window).height() - height_space) {                    height = parseInt($(window).height() - height_space, 10);                } else {                    height = parseInt(height, 10) || 300;                    //set a default height 300 for ie9-                }                var fopArr = [];                fopArr.push({                    fop: 'imageView2',                    mode: 3,                    h: height,                    q: 100,                    format: 'png'                });                fopArr.push({                    fop: 'watermark',                    mode: 1,                    image: 'http://www.b1.qiniudn.com/images/logo-2.png',                    dissolve: 100,                    gravity: 'SouthEast',                    dx: 100,                    dy: 100                });                var url = Qiniu.pipeline(fopArr, key);                $('#myModal-img').on('hide.bs.modal', function() {                    $('#myModal-img').find('.btn-default').removeClass('disabled');                    $('#myModal-img').find('.text-warning').hide();                }).on('show.bs.modal', function() {                    $('#myModal-img').find('.imageView').find('a:eq(0)').addClass('disabled');                    $('#myModal-img').find('.watermark').find('a:eq(3)').addClass('disabled');                    $('#myModal-img').find('.text-warning').hide();                });                initImg(url, key, height);                return false;            });            var ie = Qiniu.detectIEVersion();            if (!(ie && ie <= 9)) {                var exif = Qiniu.exif(res.key);                if (exif) {                    var exifLink = $('<a href="" target="_blank">查看exif</a>');                    exifLink.attr('href', url + '?exif');                    infoWrapper.append(exifLink);                }                var imageInfo = Qiniu.imageInfo(res.key);                var infoArea = $('<div/>');                var infoInner = '<div>格式:<span class="origin-format">' + imageInfo.format + '</span></div>' +                    '<div>宽度:<span class="orgin-width">' + imageInfo.width + 'px</span></div>' +                    '<div>高度:<span class="origin-height">' + imageInfo.height + 'px</span></div>';                infoArea.html(infoInner);                infoWrapper.append(infoArea);            }            Wrapper.append(infoWrapper);        }).on('error', function() {            showImg.attr('src', 'default.png');            Wrapper.addClass('default');        });    }};FileProgress.prototype.setError = function() {    this.fileProgressWrapper.find('td:eq(2)').attr('class', 'text-warning');    this.fileProgressWrapper.find('td:eq(2) .progress').css('width', 0).hide();    this.fileProgressWrapper.find('button').hide();    this.fileProgressWrapper.next('.chunk-status-tr').hide();};FileProgress.prototype.setCancelled = function(manual) {    var progressContainer = 'progressContainer';    if (!manual) {        progressContainer += ' red';    }    this.fileProgressWrapper.attr('class', progressContainer);    this.fileProgressWrapper.find('td .progress').remove();    this.fileProgressWrapper.find('td:eq(2) .btn-default').hide();    this.fileProgressWrapper.find('td:eq(2) .progressCancel').hide();};FileProgress.prototype.setStatus = function(status, isUploading) {    if (!isUploading) {        this.fileProgressWrapper.find('.status').text(status).attr('class', 'status text-left');    }};// 绑定取消上传事件FileProgress.prototype.bindUploadCancel = function(up) {    var self = this;    if (up) {        self.fileProgressWrapper.find('td:eq(2) .progressCancel').on('click', function(){            self.setCancelled(false);            self.setStatus("取消上传");            self.fileProgressWrapper.find('.status').css('left', '0');            up.removeFile(self.file);        });    }};FileProgress.prototype.appear = function() {    if (this.getTimer() !== null) {        clearTimeout(this.getTimer());        this.setTimer(null);    }    if (this.fileProgressWrapper[0].filters) {        try {            this.fileProgressWrapper[0].filters.item("DXImageTransform.Microsoft.Alpha").opacity = 100;        } catch (e) {            // If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.            this.fileProgressWrapper.css('filter', "progid:DXImageTransform.Microsoft.Alpha(opacity=100)");        }    } else {        this.fileProgressWrapper.css('opacity', 1);    }    this.fileProgressWrapper.css('height', '');    this.height = this.fileProgressWrapper.offset().top;    this.opacity = 100;    this.fileProgressWrapper.show();};

效果图



0 0
原创粉丝点击