当前位置: 首页 > 工具软件 > Qiniu PHP SDK > 使用案例 >

七牛云 php sdk 查看 上传(单文件,多文件) 删除

巫马善
2023-12-01

下载sdk  

打开php扩展中的php_curl 
upload_max_filesize 20M 更改上传文件的大小 
max_execution_time 0 
php上传大于9M 上传找不到文件名,因为上传时间默认30s,所以需要修改php.ini里的相关的参数 详情 

前端 (单文件)

思路     上传文件到服务器 再上传到本地数据库

 

<!DOCTYPE html>
<html lang="zh">

    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>Document</title>
    </head>

    <body>
        <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
        <form id="editForm" name="login_form" method="post" enctype="multipart/form-data">
            <!--<form method="post" action="up.php" enctype="multipart/form-data">-->
            <input name="file" type="file" />
            <input type="button" onclick="ajaxSubmit()" value="提交" />
        </form>

        <script type="text/javascript">
            function ajaxSubmit() {
                // 1.创建一个FormData对象,直接把我们的表单传进去  
                var formData = new FormData(document.forms.namedItem("login_form"));
                console.log(formData);
                // 2.通过jquery发送出去
                $.ajax({
                    url: "./up.php",
                    type: "POST",
                    data: formData,
                    processData: false, // 告诉jQuery不要去处理发送的数据
                    contentType: false // 告诉jQuery不要去设置Content-Type请求头
                }).success(function(res) {
                    var res = JSON.parse(res);
                    console.log(res);
                    console.log(res.key);
                    upDataToDb(res.key);
                }).error(function(err) {
                    console.log('fail!')
                });

                function upDataToDb(value) {
                    $.ajax({
                        url: "./upDataToDb.php",
                        type: "get",
                        data: {
                            name:value.split(".")[0],
                            route:"http://p6c8flnz0.bkt.clouddn.com/" + value
                        },
                    }).success(function(res) {
                        console.log(res);
                    }).error(function(err) {
                        console.log('fail!')
                    });
                }
            }
        </script>
    </body>

</html>

后端(单文件)

上传 用这里的代码 use Qiniu\Storage\UploadManager;

<?php
include "./autoload.php";
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
header("Content-type: text/html; charset=utf-8");


$bucket = '';//七牛云建立的项目
$accessKey = '';// 七牛云的信息  自己去找
$secretKey = '';//七牛云的信息  自己去找

$expires = 6000;
$auth = new Auth($accessKey, $secretKey);


$policy = array(
    //'callbackUrl' => 'http://micuer.com/qiniuyun/examples/upload_verify_callback.php',
    'callbackBody' => 'key=$(key)&hash=$(etag)&bucket=$(bucket)&fsize=$(fsize)&name=$(x:name)',
    'callbackBodyType' => 'application/json'
);
$token = $auth->uploadToken($bucket, null, $expires, $policy, true);
// 构建 UploadManager 对象
$uploadMgr = new UploadManager();

// 要上传文件的本地路径
$filePath = $_FILES['file']['tmp_name'];

$fileName = $_FILES['file']['name']; 
// 上传到七牛后保存的文件名
//$key = date("YmdH");
$key = $fileName;

list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
//echo "\n====> putFile result: \n";
if ($err !== null) {
//    var_dump($err);
      echo  $err;
} else {
//    var_dump($ret);
      echo  json_encode($ret);
}

多文件上传

element-ui
<el-upload ref="musicFile" drag class="" action="" :multiple="true" :file-list="audio_upload_files" list-type="picture" :auto-upload="false" :on-change="add_audio_change" :on-remove="del_audio" :on-preview="audio_pre">
    <i class="el-icon-upload"></i>
    <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
</el-upload>
<el-button type="primary" @click="onSubmit">立即上传</el-button>

onSubmit() { //提交数据
    let _this = this;
    var formData = new FormData();
    for (var i = 0; i < this.audio_upload_files.length; i++) {
        formData.append("file[]", this.audio_upload_files[i].raw);
    }
    this.loading = true;
    this.$http({
        url: '/qiniuyun/up_1.php',
        method: 'post',
        data: formData,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    }).then((res) => {
        console.log("上传七牛云");
        console.log(res);

    })

},

<!--重点  后台-->
// 要上传文件的本地路径
$filePath = $_FILES['file']['tmp_name'];

$fileName = $_FILES['file']['name'];

for ($i=0; $i<count($fileName); $i++) {
   list($ret, $err) = $uploadMgr->putFile($token, $fileName[$i], $filePath[$i]);
	if ($err !== null) {
	    echo  $err;
	} else {
	    echo  json_encode($ret);
	}
}

查看

方法在这里 use Qiniu\Storage\BucketManager;

<?php
include "./autoload.php";
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
header("Content-type: text/html; charset=utf-8");


$bucket = '';
$accessKey = '';
$secretKey = '';

$expires = 6000;
$auth = new Auth($accessKey, $secretKey);


$policy = array(
    //'callbackUrl' => 'http://micuer.com/qiniuyun/examples/upload_verify_callback.php',
    'callbackBody' => 'key=$(key)&hash=$(etag)&bucket=$(bucket)&fsize=$(fsize)&name=$(x:name)',
    'callbackBodyType' => 'application/json'
);
$token = $auth->uploadToken($bucket, null, $expires, $policy, true);
// 构建 UploadManager 对象
$bucketMgr = new BucketManager($auth);

list($ret, $err) = $bucketMgr->listFiles($bucket);
if ($err !== null) {
    echo ["err"=>1,"msg"=>$err,"data"=>""];
} else {
    //返回图片的完整URL
    var_dump($ret);
}

删除

方法在 use Qiniu\Storage\BucketManager;

<?php
include "../conn.php";
include "./autoload.php";
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
header("Content-type: text/html; charset=utf-8");

$key = $_GET["key"];
$bucket = '';
$accessKey = '';
$secretKey = '';

$expires = 6000;
$auth = new Auth($accessKey, $secretKey);


$policy = array(
    //'callbackUrl' => 'http://micuer.com/qiniuyun/examples/upload_verify_callback.php',
    'callbackBody' => 'key=$(key)&hash=$(etag)&bucket=$(bucket)&fsize=$(fsize)&name=$(x:name)',
    'callbackBodyType' => 'application/json'
);
$token = $auth->uploadToken($bucket, null, $expires, $policy, true);
// 构建 UploadManager 对象
$bucketMgr = new BucketManager($auth);

$err = $bucketMgr->delete($bucket,$key);

if ($err !== null) {  
    echo 0;  
    return;
    }  

echo  1; 

conn.php

<?php
    $conn=@mysql_connect("localhost","root","") or die (mysql_error());
    mysql_select_db("***", $conn);
    mysql_query("set names 'utf8' ");
    date_default_timezone_set('PRC'); 
    header('Access-Control-Allow-Origin: *');//允许跨域  很重要
    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
    header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE');
?>

 

 类似资料: