最近要做一个上传文件到七牛的功能,没看官方文档之前认为蛮简单的,看完之后就蒙比了。太乱了吧,也许是搞的太晚了,没心思认真看文档。废话不多说了
流程:前端先get后端的uptoken,选择文件后上传到七牛,七牛上传成功重定向到设置的back页面,end
1.前端代码(这里参考了[http://www.tuicool.com/articles/MZzE3eU] 和 [https://smohan.im/blog/ygbey7])
//html
<el-form-item label="上传附件">
<el-upload
class="upload-demo"
action="//up.qbox.me/"
type="drag"
:accept="accepts"
:before-upload="beforeUpload"
:on-success="handleSuccess"
:data="form" //uptoken 和key
:on-remove="handleRemove"
>
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png/zip文件,且不超过500kb</div>
</el-upload>
</el-form-item>
//js
export default {
data () {
return {
loading: false,
bucketHost: 'https://***********/', // 上传图片的外链域名,七牛设置的
form: { //存放获取到uptoken 和 key
token: '', //需要经过编译,并不是直接复制七牛账号里面的token
key: '' //这个key也不是七牛账号的key,key可以重命名上传的文件名,其他作用不太记得了
},
accepts: 'image/jpeg, image/jpg, image/png, image/gif, application/zip, application/x-zip-compressed',
//运行上传图片和zip文件
}
},
mounted () {
this.getUptoken()//先从服务器请求uptoken
},
methods: {
getUptoken () {
let _this = this
this.$http.jsonp(this.rootUrl2 + '/uptoken.php', { emulateJSON: true })
.then(function (response) {
_this.form.token = response.body.data
})
},
beforeUpload (file) { //每次上传文件之前设置key
let suffix = file.name
let key = encodeURI(`${suffix}`)
this.form.key = key
return this.form
}
2.php代码,这个主要3个php文件还一个src文件夹是官方php SDK里面的复制过来就可以
uptoken.php
这里要注意了:ReturnUrl 和 ReturnBody首字母一定要大写,否则重定向不成功
<?php
require_once 'autoload.php';
header('Access-Control-Allow-Origin:*');
use Qiniu\Auth;
$bucket = 'gond*******'; //你要上传七牛的空间名
$accessKey = '***********ak';
$secretKey = '************sk';
$auth = new Auth($accessKey, $secretKey);
//$upToken = $auth->uploadToken($bucket);
$policy = array(
//图片上次成功后七牛重定向的链接,不指定上传成功会报303的错
'ReturnUrl' => 'https://gongyicloud.com.cn/fileinfo.php',
'ReturnBody' => '{"fname": $(fname)}',
);
$upToken = $auth->uploadToken($bucket, null, 3600, $policy);
$array = array('code'=>'0','data' =>$upToken);
echo $_GET['callback'].'('.json_encode($array).')';
autoload.php
<?php
function 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';
fileinfo.php
<?php
header('Access-Control-Allow-Origin:*');
$ret = base64_decode($_GET['upload_ret']);
$cbody = json_decode($ret, true);
$dn = 'https://gongyiclo*********d.com/'; //七牛你自己设置的外链默认域名
error_log(print_r($cbody, true));
$url = $dn . $cbody['fname'];
error_log($url);
$stat_ = file_get_contents($url . '?stat');
$stat = json_decode($stat_, true);
$mtype = $stat['mimeType'];
$isImage = substr($mtype, 0, 6) == 'image/';
$array = array('code'=>'0','data' =>$url);
echo $_GET['callback'].'('.json_encode($array).')';
?>