Hongmu Notes
Home Summary of pitfalls How to upload files using Qiniu Cloud Object Storage with PHP? How to compress images during file upload?
Summary of pitfalls

How to upload files using Qiniu Cloud Object Storage with PHP? How to compress images during file upload?

How to upload files using Qiniu Cloud Object Storage with PHP? How to compress images during file upload?

Recently, I came across a image-sharing platform, so out of necessity, I decided to use Object Storage.

After reviewing the official documentation, I've finally been able to create what I needed – so, let me summarize it here!

How do I upload files to Qiniu Cloud Object Storage?

First, integrate the official SDK files into your project.

Then, PHP is introduced – you can write the code directly. Due to the confidentiality requirements of our business, I am only making the code for the upload functionality public!

<?php
require './vendor/autoload.php';
require('../action/class/common.php');

$file = glob('./up/*.png');

$filename = basename($file[0]);
$locfile  = $file[0];
$yunfilenam = 'score/'.$filename;

use Qiniu\Auth;
 // 引入上传类
use Qiniu\Storage\UploadManager;
  // 用于签名的公钥和私钥
$accessKey = '';
$secretKey = '';
$bucket = '';
  // 初始化签权对象
$auth = new Auth($accessKey, $secretKey);
// 计算文件大小,生成压缩率
$filesize = filesize($locfile); // 获取文件大小,单位为字节
$targetSize = 100 * 1024;
if ($filesize < 100 * 1024 && $filesize > 80 * 1024) {
    $water = 75; // 文件小于100KB,设置$water为75
} else {
    $water = intval(($targetSize / $filesize) * 100); 
}

$expires = 3600;
//持久化数据处理的上传凭证
$saveJpgEntry = \Qiniu\base64_urlSafeEncode($bucket . ":{$yunfilenam}");
$vframeJpgFop = "imageView2/0/format/jpg/q/{$water}|imageslim|saveas/" . $saveJpgEntry;
$policy = array(
    'scope' => $bucket . ':' . $filename,
    'persistentOps' => $vframeJpgFop,
    'insertOnly'    => 0,
    'persistentPipeline' => "",
);
$token = $auth->uploadToken($bucket, null, $expires, $policy, true);

// print_r($token);die;
// 初始化 UploadManager 对象并进行文件的上传。
$uploadMgr = new UploadManager();
// 调用 UploadManager 的 putFile 方法进行文件的上传。
list($ret, $err) = $uploadMgr->putFile($token, $yunfilenam, $locfile, null, 'application/octet-stream', true, null, 'v2');
echo "\n====> putFile result: \n";
if ($err !== null) {
    var_dump($err);
} else {
    var_dump($ret);    
}

Code Explanation:

This code is a PHP script that first includes two class library files:autoload.phpcommon.phpThese library files may implement certain basic functionalities. Then, use them.glob()Function selected./up/All items in the directory.pngSelect the filename of the first file and store it in a variable.$filenameMiddle.

Next, the image upload functionality is implemented using the Qiniu Cloud SDK. First, you need to prepare information such as your Qiniu Cloud access keys and bucket name; then, initialize the SDK.AuthObject – Generate Upload Credential$tokenThe compression rate is set based on the file size.$waterAnd the upload parameters are encapsulated into an array.$policyThis includes spatial names, file names, persistent data processing, etc. – final invocation.UploadManagerObjectputFile()Use the method to upload the file and determine whether the upload was successful based on the returned result. If the upload is successful, insert the file name into the MySQL database and transfer the file../up/Table of Contents →./bak/Output the table of contents and the operation results.

In summary, this code is designed to perform the following:./up/The first item in the table of contents.pngThe file is uploaded to Qiniu Cloud Space and compressed; simultaneously, the file name is inserted into the MySQL database; finally, the file is moved to./bak/catalogue.

How can I compress images when uploading a file?

In the above code:

$expires = 3600;
//持久化数据处理的上传凭证
$saveJpgEntry = \Qiniu\base64_urlSafeEncode($bucket . ":{$yunfilenam}");
$vframeJpgFop = "imageView2/0/format/jpg/q/{$water}|imageslim|saveas/" . $saveJpgEntry;
$policy = array(
    'scope' => $bucket . ':' . $filename,
    'persistentOps' => $vframeJpgFop,
    'insertOnly'    => 0,
    'persistentPipeline' => "",
);

This section involves processing the image – compressing it and then overwriting it.

微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

Qiniu Cloud Object Storage enables simple PHP file uploads.

Qiniu Cloud Object Storage enables simple PHP file uploads. Summary of pitfalls

Qiniu Cloud Object Storage supports simple file uploads; the official documentation also provides upload code examples. The following code can be used to test file uploads—simply replace the placeholders with your own access key and storage bucket name. <?php require 'vendor/autoload.php'; use Qiniu\Auth; // Import the upload class use Qiniu\Storage\Uploa...
👁 193
How can I download files from my private storage using Qiniu Cloud Object Storage with PHP?

How can I download files from my private storage using Qiniu Cloud Object Storage with PHP? Summary of pitfalls

To download a file from a Qiniu Cloud Private Space, you first need to obtain its download link. You can follow these steps to do so: 1. Obtain the download domain name for your private space: -In the Qiniu Cloud backend, select the corresponding storage space. -Navigate to the "Domain Settings" page. -Locate the download domain name for your private space (e.g., http://<domain>); note this address for later use. 2. Generate a download link: Use the Qiniu Cloud PHP SDK...
👁 179
After enabling the Private Space feature in Qiniu Cloud Object Storage and subsequently activating the Timestamp-based Anti-Link Hijacking feature, how can you retrieve a download link using PHP?

After enabling the Private Space feature in Qiniu Cloud Object Storage and subsequently activating the Timestamp-based Anti-Link Hijacking feature, how can you retrieve a download link using PHP? Summary of pitfalls

This tool is really handy! After enabling the private space feature in Qiniu Cloud Object Storage, the timestamp-based防盗 linking feature was also activated. How can you obtain a download link? When the timestamp verification feature is enabled for your Qiniu Cloud Object Storage private space, you need to include a timestamp parameter when generating a temporary download link. Here are the specific steps: To obtain the download domain name for your private space: In the Qiniu Cloud backend, select the corresponding storage space, navigate to the "Domain Name Settings" page, and locate the section for the private space...
👁 212
Qiniu Cloud – Are there any ways to prevent unauthorized transactions on my object storage account?

Qiniu Cloud – Are there any ways to prevent unauthorized transactions on my object storage account? Summary of pitfalls

The CDN supports various防盗链配置 options; different防盗链 mechanisms are suitable for different application scenarios. It is recommended to configure the following in the "CDN> Domain Name Management> Configuration> Access Control" section: 1. Referer-based防盗链: Only HTTP requests that include the corresponding Referer HTTP header can access the resource. However, from a technical perspective, the Referer header can be forged...
👁 375
What does "CDN return traffic" mean?

What does "CDN return traffic" mean? Summary of pitfalls

CDN origin traffic refers to the data transfer volume that occurs when a user requests content hosted on a CDN node; if the requested content is not cached at that node or if the cached content has expired, the CDN will send a request to the origin server to retrieve the original content, then transmit that content back to the CDN node over the network, and finally deliver it to the user. The amount of data transferred during this process is known as origin traffic. The primary purpose of a CDN is to cache content at nodes located as close as possible to the end users...
👁 342
What does outbound traffic to the external network mean in Object Storage?

What does outbound traffic to the external network mean in Object Storage? Summary of pitfalls

In object storage, external outbound traffic refers to the volume of data transmitted from the data center within the object storage service to the public internet. External outbound traffic is generated whenever a user downloads or accesses an object stored in the object storage service. The calculation of external outbound traffic is typically based on the total amount of data transferred, measured in bytes. This includes the amount of data transmitted to users over protocols such as HTTP, HTTPS, FTP, and others. The generation of external outbound traffic is primarily...
👁 476

Recommended reading

Hotel Guest Room Website Template 0234

Hotel Guest Room Website Template 0234 Practical Collection Yiyou template

An EyouCMS website template designed for the hotel, guesthouse, and guest room service industries. Its warm and comfortable design effectively showcases the hotel environment, room amenities, service offerings, and online booking functionality. This template helps hotels and guesthouses attract visitors online and enhance their brand awareness. Template Preview | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS...
👁 49
(PC+WAP) Socks Manufacturer Website – pbootCMS Template; Custom Knit Socks Industry Website Source Code Download – 0118

(PC+WAP) Socks Manufacturer Website – pbootCMS Template; Custom Knit Socks Industry Website Source Code Download – 0118 Practical Collection pbootcms Template

A PbootCMS website template dedicated to sock manufacturing and custom knitting services for the sock industry, compatible with both PC and WAP devices. Its stylish and minimalist design effectively showcases a variety of sock products and custom manufacturing processes. This template enables sock manufacturers or brand owners to establish an official online presence and expand their wholesale and retail distribution channels. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www...
👁 40
Home Textiles & Interior Decoration Website Template – 0905

Home Textiles & Interior Decoration Website Template – 0905 Practical Collection Yiyou template

An EyouCMS website template designed for the home textiles and home decor industry. Its warm and practical design style is ideal for showcasing home textile products, home decor items, soft furnishing combinations, and brand identities. This template helps home textile brands showcase their products online and attract domestic consumers. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS (E...
👁 39
(Adaptive mobile phone) license plate intelligent recognition system website pbootcms template parking system website source code download 0760

(Adaptive mobile phone) license plate intelligent recognition system website pbootcms template parking system website source code download 0760 Practical Collection pbootcms Template

An intelligent license plate recognition and parking system PbootCMS website template that supports PC and WAP. The design style is technological and professional, suitable for displaying license plate recognition, access control systems, and smart parking solutions. It helps smart security companies display their products online and attract property management and municipal customers. Template display Installation instructions Website backend:/admin.php Account: admin Password: admin Unzip password: www...
👁 43
Responsive Lighting Chandelier Website Template 0235

Responsive Lighting Chandelier Website Template 0235 Practical Collection Yiyou template

This EyouCMS responsive template is ideal for the lighting and chandelier industry. Its modern and bright design effectively showcases lighting products, lighting design solutions, project cases, and brand identity. It helps lighting brands showcase their products online and attract both commercial and residential renovation clients. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | Eyou...
👁 48