七牛云上传图片(tp5)

参考网址:https://www.cnblogs.com/adobe-lin/p/7699638.html
https://blog.csdn.net/qq_27808305/article/details/78348337
先来前台html

<!--先把这个文件放到this里面-->
 <input type="file" value="" onchange="uploadImg(this)"/>

再来jq(有待改进)

var xhr;
function createXMLHttpRequest() {
    if (window.ActiveXObject) {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    }
}
function uploadImg(my,url)
{
    var fileObj = my.files[0];//document.getElementById("file").files[0];
    var FileController = url; //请求地址
    var form = new FormData();
    form.append("myfile", fileObj);
    createXMLHttpRequest();
    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4){
            if (xhr.status == 200 || xhr.status == 0){
                layer.msg("上传成功")
                var result = xhr.responseText;
                if(url.indexOf("location") != -1){
                    var json = eval("("+result+")");
                    var imgurl = json.data;
                }else{
                    var imgurl = result;
                }
                // 这边能有效的防止一个编辑界面有多个上传图片的
                $(my).parent().next().append("<img src='"+imgurl+"' style='width: 100px;height: 100px;'>")
                $(my).next().val(imgurl);
                $(my).parent().next().html("<img src='"+imgurl+"' style='width: 100px;height: 100px;'>")
            }
        };
    };
    xhr.open("post", FileController, true);
    xhr.send(form);
}

最后关键的七牛来了
先composer.json那加一行”gmars/tp5-qiniu”: “dev-master”,然后composer update,然后在配置文件中写数组

  'qiniu' => [
        'accesskey' => '111',
        'secretkey' => '111',
        'bucket' => 'moreshine',
        'domain'=>'http://p11bmws2p.bkt.clouddn.com',// 你配置的空间存储域名
    ]

然后就是你自己的方法那写东西了

public function upload(){
        // 图片的本地路径
        $file = $_FILES['myfile']['tmp_name'];
        // 制作文件名
        $pathInfo = pathinfo($file);
        $ext = $pathInfo['extension'];
        $key = date('Y').'/'.date('m').'/'.date('YmdHis').mt_rand(0,9999).'.'.$ext;
        // 读取配置
        $qiniuConfig = Config::get('qiniu');
        Vendor('gmars.tp5-qiniu.qiniu_driver.autoload');
        // 初始化签权对象
        $auth = new Auth($qiniuConfig['accesskey'], $qiniuConfig['secretkey']);
        // 生成上传Token
        $token = $auth->uploadToken($qiniuConfig['bucket']);
        $uploadMgr = new UploadManager();
        // 1.token 2.加密后的文件名 3.文件所在地方
        list($ret,$err) = $uploadMgr->putFile($token,$key,$file);
        $imgUrl = $qiniuConfig['domain'].'/'.$ret['key'];
        echo $imgUrl;
    }

这个就直接的是返回你传的图片的地址,over。

猜你喜欢

转载自blog.csdn.net/wt1286331074/article/details/80450272