PHP uses the qiniu cloud storage Image Upload, download, 303 redirection tutorial, CI framework instance,

Source: Internet
Author: User

PHP uses the qiniu cloud storage Image Upload, download, 303 redirection tutorial, CI framework instance,

In addition to the API documentation on the official website, the tutorials on qiniu cloud storage on the Internet contain too little information. After studying the API, you can now upload, download, and redirect images.

First, the functions of this article are as follows:

1. with the form upload function, you can click the select file button, select a local file, set the name of the uploaded image, and click the upload button to upload and store the image to qiniu cloud storage.

2. When you Click Upload, the system will check the file suffix, which must be saved in jpg or png format.

3. After the upload is successful, jump to a set URL and return the file information, such as the file name. Instead of displaying the json display page of qiniu white flowers.

Well, let's get started. First, we need a qiniu cloud storage account. If not, apply for it by yourself.

Qiniu cloud storage Portal: http://www.qiniu.com/

1. Download the SDK

Https://github.com/qiniu/php-sdk/tags

Click this URL to download the SDK, which encapsulates the methods for uploading, downloading, and so on. We can call the SDK directly after it is introduced.

There is a qiniu folder in the SDK, which is the most important and all SDK products are available. First, we need to put the folder and the files in it into the project folder, for example, put it here.


You can see that there is a qiniu folder. Well, this is the case with resource support. Next we will implement the code.

Ii. File Upload.

1. First, let's take a picture of the key of your qiniu cloud storage. Click account settings and you will see an AccessKey and SecretKey for backup.

2. Generate the upload credential.

Here, we first need to introduce the rs. php file and find a pair of corresponding paths. The Code is as follows:

require_once(dirname(__FILE__)."/../../qiniu/rs.php");
Dirname () refers to the absolute path. Sometimes there may be problems with the relative path. We recommend that you add the dirname method before to obtain the absolute path.

Require_once indicates that the file is introduced only once.

Then, input your AccessKey and SecretKey

The Code is as follows:

$ AccessKey = 'secret'; // replace it with your own key $ secretKey = 'secret'; // replace it with your own key Qiniu_SetKeys ($ accessKey, $ secretKey );
Create an upload policy object and pass in your bucket. the bucket is your space name.

$bucket = 'designpartners';$putPolicy = new Qiniu_RS_PutPolicy($bucket);
Then, call this method to generate the upload credential.

$upToken = $putPolicy->Token(null);
Next, write an html form.

<Form method = "post" action = "http://up.qiniu.com" name = "form" enctype = "multipart/form-data"> <ul> <input type = "hidden" id =" token "name =" token "value = <? Php echo $ upToken?> <Li> <label for = "key"> key: </label> <input name = "key" value = ""> </li> <label for = "bucket"> photo: </label> <input name = "file" type = "file"/> </li> <input type = "submit" value = "submit"> </ li> </ul> </form>
Enter up.qiniu.com as the action. The form provides an input box key to enter the name of the image you want to save. This is the name after uploading it to qiniu.

Select a file and click Submit. The running result is as follows:


Enter the key value and select a photo to upload the photo. Haha is it easy.

Iii. File Download

The principle is similar to the file upload function.

Import File

require_once(dirname(__FILE__)."/../../qiniu/rs.php");
Declare your qiniu cloud storage domain name and two keys and the name of the downloaded file

$key = '00000';$domain = 'designpartners.qiniudn.com';$accessKey = 'IOImn35KC5p3scxbYkvNk6oIxB7zWsBRp16';$secretKey = 's29vc9tlCvs23wCDmIbUSi4EroKj1z';
Note: 1. The key value is the file name. Do not add a suffix.

2. domain: Add qiniudn.com to the bucket. In this example, designpartners is the bucket name I used to upload images.

3. Replace the accessKey and secretKey with your own accessKey. I can't do it directly because I modified it.

Qiniu_SetKeys($accessKey, $secretKey);  $baseUrl = Qiniu_RS_MakeBaseUrl($domain, $key);$getPolicy = new Qiniu_RS_GetPolicy();$privateUrl = $getPolicy->MakeRequest($baseUrl, null);echo $privateUrl . "\n";
Input these four values to generate the same url. You can directly access the url to download the image.

Directly Import images

You can introduce the image. It's easy. 

Iv. 303 redirection

In the above method, after the image is uploaded successfully, it will jump to up.qiniu.com, and a white web page will be displayed, showing a json string. However, in actual website development, we certainly cannot let users see this web page, so we used 303 redirection. The SDK also encapsulates this method for us. It is actually very simple to use. Add two lines of code to the Code for uploading files.

$putPolicy = new Qiniu_RS_PutPolicy($bucket);$putPolicy->ReturnUrl = site_url()."/upload/receiveInfo";$putPolicy->ReturnBody='{"key": $(key)}';
Note: 1. ReturnUrl and ReturnBody must be specified, and the first letter must be in upper case. Many people start with lower case, so the jump will fail.

2. The ReturnUrl must be accessible from the public network. It is impossible to pass the local test. For example, if you write localhost, The qiniu server cannot be located.
3. Will the ReturnUrl link be followed by? Upload_ret = XXX. You can use the get method to obtain this upload_ret. The content of upload_ret is a base64 encoded json key value.

Value parsing: for example, the uploaded file name is 555

upload/receiveInfo?upload_ret=eyJrZXkiOiAiNTU1In0=
The URL suffix is shown above. Copy the upload_ret file and use base64 to decode it. The following result is displayed:

{"key": "555"}
Therefore, the code for getting the value 555 is as follows:

$upload_ret = $_GET['upload_ret'];$json_ret = base64_decode($upload_ret);$result=json_decode($json_ret);echo "key".$result->key; 
After obtaining the key value, you can save it to the database or perform other operations.

V. file type verification before upload

We can use js to verify the file suffix,

Add

onsubmit="return isValidateFile('file');"
Add a js method

<Script> function isValidateFile (obj) {var extend = document. form. file. value. substring (document. form. file. value. lastIndexOf (". ") + 1); if (extend =" ") {alert (" select Avatar "); return false;} else {if (! (Extend = "jpg" | extend = "png") {alert ("upload a file with the suffix jpg or png! "); Return false ;}} return true ;}</script>

To verify that its type is valid.

Appendix: CI code implementation:

Get Uptoken:

Function getUptoken () {require_once (dirname (_ FILE __). "/.. /.. /qiniu/rs. php "); // remote bucket name $ bucket = 'design'; $ accessKey = 'bucket'; $ secretKey = 'bucket'; Qiniu_SetKeys ($ accessKey, $ secretKey ); $ putPolicy = new Qiniu_RS_PutPolicy ($ bucket); echo site_url (); $ putPolicy-> ReturnUrl = site_url (). "/upload/receiveInfo"; $ putPolicy-> ReturnBody = '{"key": $ (key)}'; $ upToken = $ putPolicy-> Token (null ); return $ upToken ;}
File Upload:

public function uploadPic(){$upToken = $this->getUptoken();        $data['upToken'] = $upToken;$this->load->view('upload',$data);}
303 redirection Resolution:

public function receiveInfo(){$upload_ret = $_GET['upload_ret'];$json_ret = base64_decode($upload_ret);$result=json_decode($json_ret);echo "key".$result->key; }
File Download:

public function downloadPic(){require_once(dirname(__FILE__)."/../../qiniu/rs.php");$key = '00000';$domain = 'designpartners.qiniudn.com';$accessKey = 'IOImn35KC57Ov3scxbYkvNk6oIxB7zWsBRp16';$secretKey = 's29vc9tlCvsh7QScYTuzCDmIbUSi4EroKj1z';Qiniu_SetKeys($accessKey, $secretKey);  $baseUrl = Qiniu_RS_MakeBaseUrl($domain, $key);$getPolicy = new Qiniu_RS_GetPolicy();$privateUrl = $getPolicy->MakeRequest($baseUrl, null);echo "====> getPolicy result: \n";echo $privateUrl . "\n";}
Form:

<Script> function isValidateFile (obj) {var extend = document. form. file. value. substring (document. form. file. value. lastIndexOf (". ") + 1); if (extend =" ") {alert (" select Avatar "); return false;} else {if (! (Extend = "jpg" | extend = "png") {alert ("upload a file with the suffix jpg or png! "); Return false ;}} return true ;} </script> <form method = "post" action = "http://up.qiniu.com" name = "form" enctype = "multipart/form-data" onsubmit = "return isValidateFile ('file '); "> <ul> <input type =" hidden "id =" token "name =" token "value = <? Php echo $ upToken?> <Li> <label for = "key"> key: </label> <input name = "key" value = ""> </li> <label for = "bucket"> photo: </label> <input name = "file" type = "file"/> </li> <input type = "submit" value = "submit"> </ li> </ul> </form>




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.