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

网络编程 2021-07-05 08:24www.168986.cn编程入门
这篇文章主要介绍了PHP上传文件及图片到七牛的方法,长沙网络推广觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随长沙网络推广过来看看吧

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

安装PHP SDK

poser require qiniu/php-sdk

上传文件到七牛

use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

$cfg = [
 'aess' => 'YOUR_ACCESS_KEY',
 'secret' => 'YOUR_SECRET_KEY',
 'bucket' => 'YOUR_BUCKET',
 'domain' => 'https://images.your_domain.'
];

$auth = new Auth($cfg['aess'], $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('Aess-Control-Allow-Origin:');

use Qiniu\Auth;

$bucket = '要上传的空间名';
$aessKey = '你的aessKey';
$secretKey = '你的secretKey';
$auth = new Auth($aessKey, $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_set($ch, CURLOPT_URL,$remote_server); 
 //curl_set($ch, CURLOPT_HEADER, 0);
 curl_set($ch, CURLOPT_HTTPHEADER ,$headers);
 curl_set($ch, CURLOPT_RETURNTRANSFER, 1); 
 //curl_set($ch, CURLOPT_POST, 1);
 curl_set($ch, CURLOPT_POSTFIELDS, $post_string);
 curl_set($ch, CURLOPT_CONNECTTIMEOUT, 10);
 curl_set($ch, CURLOPT_TIMEOUT, 30);
 $data = curl_exec($ch); 
 curl_close($ch); 
 
 return $data; 
} 
$str="base64编码的字符串";
echo "<pre>";
echo request_by_curl('http://upload.qiniu./putb64/-1',$str,$upToken);
echo "</pre>";

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

Copyright © 2016-2025 www.168986.cn 狼蚁网络 版权所有 Power by