PHP Method of Uploading Files and Pictures to Seven Cows

  • 2021-10-24 19:14:12
  • OfStack

The easiest way to upload files to 7 Niu is to use the latest SDK of 7 Niu official

Installing PHP SDK


composer require qiniu/php-sdk

Upload files to 7 N.


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']);
//  Create 1 The expiration time is 1 Temporary upload token for hours 
$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 uploads base64 encoded pictures to 7 cows

Share my code with you for 1 time:


<?php
require_once 'vendor/autoload.php';
header('Access-Control-Allow-Origin:*');

use Qiniu\Auth;

$bucket = ' The name of the space to upload ';
$accessKey = ' Yours accessKey';
$secretKey = ' Yours secretKey';
$auth = new Auth($accessKey, $secretKey);
$upToken = $auth->uploadToken($bucket, null, 3600);// Object required for upload 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 Encoded string ";
echo "<pre>";
echo request_by_curl('http://upload.qiniu.com/putb64/-1',$str,$upToken);
echo "</pre>";


Related articles: