欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

PHP上传文件及图片到七牛的方法

程序员文章站 2022-04-14 09:37:36
上传文件到七牛最简单的方式就是使用七牛官方最新的sdk 安装php sdk composer require qiniu/php-sdk 上传文件到七牛...

上传文件到七牛最简单的方式就是使用七牛官方最新的sdk

安装php sdk

composer require qiniu/php-sdk

上传文件到七牛

use qiniu\auth;
use qiniu\storage\uploadmanager;

$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 qiniu\auth;

$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>";

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。