php上传文件与图片到七牛的实例详解
Posted lxwphp
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php上传文件与图片到七牛的实例详解相关的知识,希望对你有一定的参考价值。
上传文件到七牛最简单的方式就是使用七牛官方最新的SDK
用composer安装php SDK
composer require qiniu/php-sdk
上传文件到七牛
use QiniuAuth;
use QiniuStorageUploadManager;
$cfg = [
‘access‘ => ‘YOUR_ACCESS_KEY‘,
‘secret‘ => ‘YOUR_SECRET_KEY‘,
‘bucket‘ => ‘YOUR_BUCKET‘,
‘domain‘ => ‘https://images.your_domain.com‘
];
$auth = new Auth($cfg[‘access‘], $cfg[‘secret‘]);
// 创建一个过期时间为1小时的临时上传令牌
$token = $auth->uploadToken($cfg[‘bucket‘], null, 3600);
$filePath = "./illustration.png";
$uploadMgr = new UploadManager();
list($ret, $err) = $uploadMgr->putFile($token, null, $filePath);
if($err !== null) {
$this->err = $err;
} else {
echo $cfg[‘domain‘] . ‘/‘ . $ret[‘key‘];
}
php向七牛上传base64编码的图片
<?php
require_once ‘vendor/autoload.php‘;
header(‘Access-Control-Allow-Origin:*‘);
use QiniuAuth;
$bucket = ‘要上传的空间名‘;
$accessKey = ‘你的accessKey‘;
$secretKey = ‘你的secretKey‘;
$auth = new Auth($accessKey, $secretKey);
$upToken = $auth->uploadToken($bucket, null, 3600);//获取上传所需的token
function request_by_curl($remote_server,$post_string,$upToken) {
$headers = array();
$headers[] = ‘Content-Type:image/png‘;
$headers[] = ‘Authorization:UpToken ‘.$upToken;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$remote_server);
//curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER ,$headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$str="base64编码的字符串";
echo "<pre>";
echo request_by_curl(‘http://upload.qiniu.com/putb64/-1‘,$str,$upToken);
echo "</pre>";
以上是关于php上传文件与图片到七牛的实例详解的主要内容,如果未能解决你的问题,请参考以下文章
ueditor1.4.3 php如何上传图片到图片服务器(七牛)
php表单上传图片到七牛云存储并返回地址……求具体流程~有代码更好