php上传图片到个人百度网盘

21-09-01     slbcun     723℃     0

平时使用百度网盘,都是下载网盘客户端来上传和下载文件。如果想要在系统中使用百度网盘的上传和下载,肯定要用程序来操作客户端。

好在,百度网盘开放平台提供了各种实用的接口,在我们开发的程序中,只需要调用接口,就能够完成文件的上传和下载功能。

在百度网盘开发平台中提供的各种接口文档虽然比较详细,但是没有demo,有些问题上还是容易卡住,本文结合百度网盘开放平台的接口和其他的百度接口来实现网盘文件的操作,包括授权登录,文件列表,文件信息,上传(分片)文件,下载文件,删除文件,创建文件夹


1.登录百度网盘开放平台,网址:https://pan.baidu.com/union/home,点击右上角的控制台,进入后点击创建应用


php上传图片到个人百度网盘


php上传图片到个人百度网盘

2.创建应用后记下应用密钥,密钥,签名密钥,别忘了填写oauth授权页面地址


php上传图片到个人百度网盘

3.jquery获取上传文件,判断文件大小小于2G直接上传,大于2G分片上传

var chunkSize = 1024 * 1024 * 1024 * 2; // 单个分片大小
var chunkList = []; // 分片数据列表
var file = null; // 上传文件
var activeChunk = 0; // 已完成的分片数量
var chunkSum = 0;  //分片数量
var filesize = 0; //文件大小
var filename = ''; //文件名称
var sku = 'doc_name'; //上传文件夹名称

var cl = '';  //上传点击按钮
var tplj = '';


$(document).on("change",cl,function(e) {
    files = e.target.files;
    if(files['length'] == 1){
        file = e.target.files[0];
        filesize = file.size;
        filename = file.name;

        setChunkFile(file);
        if (!chunkList) return;
        activeChunk = 0;
        chunkSum = chunkList.length;
        for(var i = 0; i < chunkSum; i++) {
            uploadChunk(chunkList[i], i, chunkSum,0);//上传分片
        }
    }
    if(files['length'] > 1){
        for(var n=0;n<files['length'];n++){
            file = e.target.files[n];
            filesize = file.size;
            filename = file.name;

            setChunkFile(file);
            if (!chunkList) return;
            activeChunk = 0;
            chunkSum = chunkList.length;
            for(var i = 0; i < chunkSum; i++) {
                uploadChunk(chunkList[i], i, chunkSum,n);//上传分片
            }
        }
    }
});

/**
 * 切割文件到分片列表
 * @param {[type]} file [description]
 */
function setChunkFile(file) {
    chunkList = [];
    var s = e = 0;
    var chunkNum = Math.ceil(filesize/chunkSize);
    while(true) {
        if (e >= filesize) {
            e = filesize;
            break;
        }
        e = s + chunkSize;
        var slices = file.slice(s, e);
        chunkList.push(slices);
        s = e;
    }
}

/**
 * 百度云上传
 * @param  {[type]} file  [description]
 * @param  {[type]} index [description]
 * @return {[type]}       [description]
 */
function uploadChunk(file, index,chunkSum,n,m) {
    var fd = new FormData();
    fd.append('sku', sku);
    fd.append('index', index);
    fd.append('chunksum', chunkSum);
    fd.append('filename', filename);
    fd.append('filesize', filesize);
    fd.append('file', file);
    Fast.api.ajax({
        type: 'post',
        url: 'baiduimg/upload',
        dataType: 'json',
        contentType: false,
        processData: false,
        data: fd,
    }, function(data,ret){
        if (ret.code == 1) {
            activeChunk++;
            if (activeChunk == chunkList.length) {
                console.log('分片上传完成');
            }else {
                console.log('分片'+index+'上传成功,即将进行下一分片上传');
            }
            if(ret.msg){
                var n_tplj = $("#"+tplj).val();
                var appimg = '<li class="col-xs-3"><a href="'+ret.msg+'" data-url="'+ret.msg+'" target="_blank" class="thumbnail"><img src="'+ret.msg+'" onerror="this.src=\'/stark.php/ajax/icon?suffix=jpg\';this.onerror=null;" class="img-responsive"></a><a href="javascript:;" class="btn btn-danger btn-xs btn-trash"><i class="fa fa-trash"></i></a></li>';
                $("#p-link_url").append(appimg);
                if(n_tplj.length == 0){
                    $("#"+tplj).val(ret.msg);
                }else{
                    $("#"+tplj).val(n_tplj+';'+ret.msg);
                }
            }
        }
        return false;
        //成功的回调
    }, function(){
        return false;
        //失败的回调
    });
}
/**
 * 显示图片和删除按钮
 */
function deliz(){
    var scfile=$("#c-link_url").val();
    if(scfile.length > 0){
        var arr = scfile.split(';');
        for(var i in arr){
            var list = '<li class="col-xs-3"><a href="'+arr[i]+'" data-url="'+arr[i]+'" target="_blank" class="thumbnail"><img src="'+arr[i]+'" onerror="this.src=\'/stark.php/ajax/icon?suffix=jpg\';this.onerror=null;" class="img-responsive"></a><a href="javascript:;" class="btn btn-danger btn-xs btn-trash"><i class="fa fa-trash"></i></a></li>';
            $("#p-link_url").append(list);
        }
    }
}

/**
 * 删除图片
 */
$(document).on("click", ".btn-trash",function(){
    var imgurl=$(this).prev().data("url");
    Fast.api.ajax({
        url:'baiduimg/delimg',
        data:{imgurl:imgurl}
    }, function(data,ret){
        if(ret.data==1){
            $("#p-link_url").empty();
            var scfile=$("#c-link_url").val();
            var arr = scfile.split(';');
            arr.splice($.inArray(imgurl,arr),1);
            var str = arr.join(';');
            $("#c-link_url").val(str);
            deliz();
        }
        //成功的回调
    }, function(){
        return false;
        //失败的回调
    });
});

4.php后台接收数据并处理数据

$this->baidu = new baidu();
/**
 * 百度接口授权
 */
public function auth(){
    $url=$this->baidu->auth();
    $this->success("1", null, $url);
}
/**
 * 是否授权有效
 */
public function isauth(){
    $istrue=$this->baidu->isauth();
    if($istrue==1){
        $this->success("", null, 1);
    }else{
        $this->success($istrue, null, 0);
    }
}
/**
 * 百度接口回调
 */
public function baidu(){
    $code=$_GET['code'];
    $res=$this->baidu->set_access_token($code);
    if($res){
        echo "<script language=JavaScript> window.close();</script>";
    }
}

/**
 * 上传文件列表
 */
public function upload(){
    $tempath = "./tmp/";
    if (!file_exists($tempath)) {
        mkdir($tempath);
    }
    $file = $this->request->file('file');
    if($file){
        $sku = $_POST['sku'];
        $chunksum = $_POST['chunksum'];
        $index = $_POST['index'];
        $filename = $_POST['filename'];
        $filesize = $_POST['filesize'];
        $tmp_name = $_FILES['file']['tmp_name'];
        if($chunksum == 1){
            if (!file_exists($tempath . $filename)) {
                move_uploaded_file($tmp_name, $tempath . $filename);
            }
            $res = $this->baidu->upload_one($tempath,$filename,$filesize,$sku);//上传单个文件
            if($res){
                if($res['exists'] == 0){
                    $bdimg=[];
                    $bdimg['sku']=$sku;
                    $bdimg['filename']=$res['filename'];
                    $bdimg['path']=$res['path'];
                    $bdimg['fsid']=$res['fs_id'];
                    $bdimg['size']=$res['size'];
                    $bdimg['url1']=$res['thumbs']['url1'];
                    $bdimg['url2']=$res['thumbs']['url2'];
                    $bdimg['url3']=$res['thumbs']['url3'];
                    $bdimg['time']=$res['server_mtime'];
                    $this->model->insert($bdimg);
                }
                $this->success($res['thumbs']['url3'], '',['h' => 1,'r' => '上传成功']);
            }
        }else{
            if (!file_exists($tempath . $filename . '_' .$index)) {
                move_uploaded_file($tmp_name, $tempath . $filename . '_' .$index);
            }
            $res = $this->baidu->fp_upload($tempath,$filename,$filesize,$sku,$chunksum,$index);
            if($res){
                if(isset($res['exists']) && $res['exists'] == 0){
                    $bdimg=[];
                    $bdimg['sku']=$sku;
                    $bdimg['filename']=$res['filename'];
                    $bdimg['path']=$res['path'];
                    $bdimg['fsid']=$res['fs_id'];
                    $bdimg['size']=$res['size'];
                    $bdimg['url1']=$res['thumbs']['url1'];
                    $bdimg['url2']=$res['thumbs']['url2'];
                    $bdimg['url3']=$res['thumbs']['url3'];
                    $bdimg['time']=$res['server_mtime'];
                    $this->model->insert($bdimg);
                    $this->success($res['thumbs']['url3'], '',['h' => 1,'r' => '上传成功']);
                }else{
                    return true;
                }
            }

        }
    }
}

/**
 * 删除文件
 */
public function delimg(){
    if($this->request->post("imgurl")){
        $imgurl=$this->request->post("imgurl");
        $res = $this->model->where(['url3'=>$imgurl])->find();
        $path=$res['path'];
        $this->baidu->delimgs($path);
        $this->model->where('id', $res['id'])->delete(); 
        $this->success('删除成功!', '',1);
    }
}

5.百度云上传类

<?php

namespace fast;
use think\Cache;

class baidu
{
    private $AppKey;
    private $SecretKey;
    private $SignKey;
    private $redirect_uri;

    public function __construct() {
        $this->AppKey = '应用密钥';
        $this->SecretKey = '密钥';
        $this->SignKey = '签名密钥';
        $this->redirect_uri = 'OAuth授权页面地址';
    }
    /**
     * 百度接口auth授权入口
     */
    public function auth(){
        $url="https://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id=".$this->AppKey."&redirect_uri=".$this->redirect_uri."&scope=basic,netdisk&display=popup&qrcode=1&force_login=1";
        return $url;
    }
    /**
     * 是否授权有效
     */
    public function isauth(){
        $refresh_token=file_get_contents("./refresh_token.txt");
        $url="https://openapi.baidu.com/oauth/2.0/token?grant_type=refresh_token&refresh_token=".$refresh_token."&client_id=".$this->AppKey."&client_secret=".$this->SecretKey;
        $data=$this->http_curls($url,'get', '');
        $data=json_decode($data,true);
        if(isset($data['expires_in'])){
            return 1;
        }else{
            $url="https://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id=".$this->AppKey."&redirect_uri=".$this->redirect_uri."&scope=basic,netdisk&display=popup&qrcode=1&force_login=1";
            return $url;
        }
    }
    /**
     * 上传单个文件
     */
    public function upload_one($tempath,$filename,$filesize,$sku){
        $access_token=$this->access_token();
        $r = $this->is_file(urlencode('/apps/bpm/'.$sku.'/'.$filename),$access_token);
        if($r == 0){
            $url="https://pcs.baidu.com/rest/2.0/pcs/file?method=upload&access_token=".$access_token."&path=".urlencode('/apps/bpm/'.$sku.'/'.$filename);
            $post_data=fopen($tempath.$filename, 'r');
            $res=$this->http_curl($url, $post_data, $filesize);
            $res=json_decode($res,true);
            unlink($tempath . $filename);
            if($res['fs_id']){
                $rs=$this->get_info($res['fs_id']);
                $rs=json_decode($rs, true);
                $rs['list'][0]['exists']=0;
                return $rs['list'][0];
            }
        }else{
            $r[0]['exists']=1;
            return $r[0];
        }
    }
    /**
     * 分片上传文件
     */
    public function fp_upload($tempath,$filename,$filesize,$sku,$chunksum,$index){
        $access_token=$this->access_token();
        $url="https://pcs.baidu.com/rest/2.0/pcs/file?method=upload&access_token=".$access_token."&type=tmpfile";
        $post_data=fopen($tempath . $filename . '_' .$index, 'r');
        $res=$this->http_curl($url,$post_data, $filesize);
        $res=json_decode($res,true);
        unlink($tempath . $filename . '_' .$index);
        if(!empty($res['md5'])){
            Cache::set($filename."_".$index, $res['md5'], 7200);
            if($index + 1 == $chunksum){
                $r=$this->create_upload($access_token,$filename,$sku,$index,$filesize);
                return $r;
            }else{
                return true;
            }
        }else{
            print_r('分片上传出错');exit;
        }
    }

    /**
     * 分片上传创建文件
     */
    public function create_upload($access_token,$filename,$sku,$i,$filesize){
        $r = $this->is_file(urlencode('/apps/bpm/'.$sku.'/'.$filename),$access_token);
        if($r == 0){
            for($v=$i;$v>=0;$v--){
                $block_list[$v]=Cache::get($filename."_".$v);
            }
            ksort($block_list);
            $url="https://pcs.baidu.com/rest/2.0/pcs/file?method=createsuperfile&access_token=".$access_token."&path=".urlencode('/apps/bpm/'.$sku.'/'.$filename);
            $data=[];
            $data['block_list'] = json_encode($block_list,true);
            $res=$this->http_curl($url,$data, $filesize);
            $res=json_decode($res,true);
            if($res['fs_id']){
                $rs=$this->get_info($res['fs_id']);
                $rs=json_decode($rs, true);
                $rs['list'][0]['exists']=0;
                return $rs['list'][0];
            }
        }else{
            $r[0]['exists']=1;
            return $r[0];
        }
    }
    /**
     * 创建文件夹
     */
    public function create($filename,$access_token){
        $url="https://pan.baidu.com/rest/2.0/xpan/file?method=create&access_token=".$access_token;
        $data=[];
        $data['path'] = "/apps/bpm/".$filename;
        $data['size'] = 0;
        $data['isdir'] = 1;
        $data['rtype'] = 0;
        $res=$this->http_curls($url,'post', $data);
        return $res;
    }

    /**
     * 下载文件
     */
    public function download($path){
        $access_token=$this->access_token();
        $url="https://pcs.baidu.com/rest/2.0/pcs/file?method=download&access_token=".$access_token."&path=".$path;
        $this->http_curls($url,'get', '');
    }

    /**
     * 判断文件是否存在
     */
    public function is_file($path,$access_token){
        $url="https://pcs.baidu.com/rest/2.0/pcs/file?method=meta&access_token=".$access_token."&path=".$path;
        $res=$this->http_curls($url,'get', '');
        if($res){
            $res=json_decode($res,true);
            if(isset($res['list']) && count($res['list']) > 0){
                $fs_id=$res['list'][0]['fs_id'];
                $rs=$this->get_info($fs_id);
                if($rs){
                    $rs=json_decode($rs, true);
                    return $rs['list'];
                }
            }
            if(isset($res['error_code']) && $res['error_code'] == 31066){
                return 0;//文件不存在
            }
        }
    }

    /**
     * 查询单个文件信息
     */
    public function get_info($fs_id){
        $access_token=$this->access_token();
        $url="https://pan.baidu.com/rest/2.0/xpan/multimedia?method=filemetas&access_token=".$access_token."&fsids=[".$fs_id."]&thumb=1&dlink=1";
        $res=$this->http_curls($url,'get', '');
        return $res;
    }

    /**
     * 删除单个文件
     */
    public function delimgs($path){
        $url="https://pcs.baidu.com/rest/2.0/pcs/file?method=delete&access_token=".$this->access_token()."&path=".urlencode($path);
        $res=$this->http_curls($url,'get', '');
        return $res;
    }

    /**
     * 百度接口缓存access_token
     */
    public function access_token(){
        if(Cache::has('bd_token')){
            $bd_token=Cache::get('bd_token');
            if($bd_token['time'] < time()){
                $bd_token=$this->get_access_token($bd_token['refresh_token'],1);//更新缓存
            }
        }else{
            $bd_token=$this->get_access_token($this->refresh_token,1);//更新缓存
        }
        return $bd_token['access_token'];
    }
    /**
     * 百度接口缓存access_token
     */
    public function set_access_token($code)
    {
        if(!empty($code)){
            $bd_token=$this->get_access_token($code,0);//获取缓存
            $refresh_token=$bd_token['refresh_token'];
            $wjm='./refresh_token.txt';
            if(!file_exists($wjm)){
                mkdir($wjm);
            }
            file_put_contents($wjm,$refresh_token);
            return true;
        }else{
            $this->auth();
        }
    }
    /**
     * 百度接口获取access_token
     */
    public function get_access_token($s,$m){
        if($m == 1){
            $url="https://openapi.baidu.com/oauth/2.0/token?grant_type=refresh_token&refresh_token=".$s."&client_id=".$this->AppKey."&client_secret=".$this->SecretKey;
        }else{
            $url="https://openapi.baidu.com/oauth/2.0/token?grant_type=authorization_code&code=".$s."&client_id=".$this->AppKey."&client_secret=".$this->SecretKey."&redirect_uri=".$this->redirect_uri;
        }
        $data=$this->http_curls($url,'get', '');
        $data=json_decode($data,true);
        if($data['expires_in']){
            $data['time']=time()+$data['expires_in'];
            Cache::set('bd_token', $data, $data['expires_in']);
            return $data;
        }else{
            $this->success('未授权!', '',1);
        }
    }

    /**
     * 发送文件流上传文件
     * @param $url
     * @return string
     */
    function http_curl($url, $post_data, $filesize ){
        $ch =  curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
        curl_setopt($ch, CURLOPT_PUT, true);
        curl_setopt($ch, CURLOPT_INFILE, $post_data);
        curl_setopt($ch, CURLOPT_INFILESIZE, $filesize);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;

    }

    /**
     * url请求
     */
    function http_curls($url, $type, $data){
        $cl = curl_init();//初始化
        curl_setopt($cl, CURLOPT_URL, $url);//设置 cURL 传输选项
        curl_setopt($cl, CURLOPT_RETURNTRANSFER, 1);// 将curl_exec()获取的信息以字符串返回,而不是直接输出。
        curl_setopt($cl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($cl, CURLOPT_SSL_VERIFYHOST, false);
        if($type == 'post'){
            curl_setopt($cl, CURLOPT_POST, true);//发送 POST 请求,类型为:application/x-www-form-urlencoded
            curl_setopt($cl, CURLOPT_POSTFIELDS, $data);
        }
        $output = curl_exec($cl);//执行 cURL 会话
        curl_close($cl);
        return $output;
    }

}


分享 收藏
发表我的评论

表情

共0条评论
  • 这篇文章还没有收到评论,赶紧来抢沙发吧~