PHP upload, download, 303 redirect tutorials with images of seven cow cloud storage, CI framework instance

Source: Internet
Author: User

Online tutorial on the seven Qiniu storage in addition to the official Web API documentation, the other information is too small. After studying the API, it is now possible to upload and download images and redirect them after uploading.

First, this article implements the following functions:

1. Using the form upload function, the user can click the Select File button, select a local file, and also set the name of the uploaded image, click the upload button can be uploaded and stored to seven cow cloud storage.

2. When you click Upload, the suffix name of the file is detected and is limited to JPG and PNG format storage.

3. After the upload succeeds, jump to a URL that you set, and return the file information, such as the filename. Instead of displaying the JSON display page of the seven bull Shining White.

Well, let's get started, first we need to have a seven cow cloud storage account, if you do not have to apply it yourself.

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

I. SDK download

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

Poke this URL to download the SDK, which encapsulates the file upload and download methods, we can directly call after the introduction.

There is a Qiniu folder in the SDK, which is the most important of all the SDK real goods. We will first put this folder and the files in the project folder, such as I put here.


You can see there is a Qiniu folder. Well, that's the way resources are supported. Next we're going to implement the code.

Two. Upload the file.

1. First take your seven qiniu stored keys, click on the account settings can see there is a accesskey and Secretkey, reserved.

2. Upload voucher generation.

Here we first want to introduce the rs.php file, find a corresponding path, the code is as follows:

Require_once (DirName (__file__). " /.. /.. /qiniu/rs.php ");
DirName () is the absolute path, and sometimes the relative path is problematic, it is recommended to precede the DirName method to get the absolute path.

Require_once is the introduction of a file that indicates that the file was introduced only once.

Then, pass in your accesskey and Secretkey.

The code is as follows:

$accessKey = ' imn35kc5prx7ov3scxbykvnk6oix7zwsbrp16 ';  Replace your own key $secretkey = ' s29vc9tlcvs23wrh7qscytuzcdmerokj1ddssz ';    Replace your own key Qiniu_setkeys ($accessKey, $secretKey);
Then build an upload policy object, put your bucket into the bucket is your space name.

$bucket = ' designpartners '; $putPolicy = new Qiniu_rs_putpolicy ($bucket);
Then call this method to generate the upload credentials.

$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>        <li >            <label for= "Buckets" > Photos:</label>            <input name= "file"  type= "file"/>        </ li>        <li>            <input type= "Submit" value= "Submission" >        </li>    </ul></form >
Action to fill in the up.qiniu.com, the form provides an input box key, used to enter the name of the image you want to save, uploaded to seven cattle is the name.

Then a file selection, a Submit button. The results of the operation are as follows:


You can upload a photo by entering a key value and selecting a photo. Ha haha there is no very simple.

Third, File download

The principle and file upload function is similar.

Introducing Files

Require_once (DirName (__file__). " /.. /.. /qiniu/rs.php ");
Declare your seven-qiniu storage domain name and two keys and the file names that are downloaded down

$key = ' 00000 '; $domain = ' designpartners.qiniudn.com '; $accessKey = ' ioimn35kc5p3scxbykvnk6oixb7zwsbrp16 '; $secretKey = ' s29vc9tlcvs23wcdmibusi4erokj1z ';
Note: The 1.key value is the file name, do not add a suffix

2.domain is the bucket plus qiniudn.com, the example of Designpartners is the bucket name I used when uploading images.

3.accessKey and Secretkey for your own, directly with my No. 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";
Pass in these four values to generate the same URL, directly access the URL to achieve the image download.

When a picture is introduced, direct

Can introduce pictures, very simple bar.

Four, 303 redirects

In the above method, we upload the image successfully after the jump to up.qiniu.com, will display a white page, display a JSON string, but in the actual site development we certainly can not let users see this page, so we used to 303 jump. This method is also encapsulated for us in the SDK. The use is actually very simple. Add two lines of code to the code that uploads the file

$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 is capitalized, and many people start with lowercase, which jumps unsuccessfully.

2.RETURNURL must be a public network can access the URL, in the local test is not possible to pass. For example, if you write localhost, the seven-ox server is not located.
3. This returnurl link is followed by a upload_ret=xxx, which can be obtained using the Get method Upload_ret. The content of Upload_ret is a key value in JSON form of Base64 security encoding.

Value Resolution: For example, the file name I uploaded is 555.

upload/receiveinfo?upload_ret=eyjrzxkioiaintu1in0=
URL suffix as shown above, the Upload_ret copy down, with Base64 decoding can appear the following results:

{"Key": "555"}
So, the code that we want to get 555 of this value is as follows: The parsing code is as follows.

OK, after getting to this key value, you can choose to save to the database or perform other operations.

V. Verification of file types before uploading

We can use JS to verify the suffix name of the file,

In the properties of the form, 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 ("Please select Avatar"); return false;} else {if (! ( Extend = = "JPG" | | Extend = = "png") {alert ("Please upload a file with a suffix named jpg or png!"); return false;}} return true;} </script>

To verify that its type is legitimate.

Attached: CI Code implementation:

Get Uptoken:

function Getuptoken () {require_once (DirName (__file__). /.. /.. /qiniu/rs.php ");//Remote Storage space name $bucket = ' Designpartners '; $accessKey = ' ioimn35kcrx7ov3scvnk6oixb7zwsbrp16 '; $secretKey = ' s29vc9tlcvs23wrhtuzcdmibusi4erokj1z '; 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 REDIRECT parsing:

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 ("Please select Avatar"); return false;} else {if (! ( Extend = = "JPG" | | Extend = = "png") {alert ("Please upload a file with a suffix named 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= "" > &lt ;/li> <li> <label for= "Buckets" > Photos:</label> <input name= "file" type= "    File "/> </li> <li> <input type=" Submit "value=" commit "> </li> </ul></form>

php upload, download, 303 redirect Tutorials for images with seven cow cloud storage, CI framework instance

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.