Configure Thinkphp3.2 to support uploading qiniu images-PHP source code

Source: Internet
Author: User
Tags ftp file
For the qiniu Image Upload method, we only need to configure its interface and some upload details in the framework. Let's take a look at how to configure Thinkphp3.2 to support qiniu Image Upload, I hope this article will help you. For the qiniu Image Upload method, we only need to configure its interface and some upload details in the framework. Let's take a look at how to configure Thinkphp3.2 to support qiniu Image Upload, I hope this article will help you.

Script ec (2); script

As a php cainiao, I used qiniu in a thinkphp framework project in the company (I used the C # sdk ). Now, I found the official php sdk and found that Thinkphp already supports uploading files with the drive type of qiniu.

Now we will describe the configuration.

Use qiniu cloud's private space to store files


Register qiniu cloud, create a space, and set the space as private
Something to note:
AK, SK, and bucket

Add in config. php

// Qiniu Upload File Settings
'Picture _ UPLOAD_DRIVER '=> 'qiniu ',
// Local Upload File driver Configuration
'Upload _ LOCAL_CONFIG '=> array (),
'Upload _ QINIU_CONFIG '=> array (
'Accesskey' => 'l3n4q0xcqm0rssaamthryzyg-LnKMH ',
'Secrectkey' => '7qpvaerasasan2tjalqqajf0h6jot0d1jf ',
'Bucket' => 'yaasnbao ',
'Domain '=> '7xasssa .com2.z0.glb.qiniucdn.com ',
'Timeout' = & gt; 3600,
),

3. Add an upload class Model


// + ----------------------------------------------------------------------
// | OneThink [we can do it just think it]
// + ----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// + ----------------------------------------------------------------------
// | Author: huajie
// + ----------------------------------------------------------------------
Namespace Admin \ Model;
Use Think \ Model;
Use Think \ Upload;
/**
* Image model
* Uploads images.
*/
Class PictureModel extends Model {
/**
* Automatic completion
* @ Var array
*/
Protected $ _ auto = array (
Array ('status', 1, self: MODEL_INSERT ),
Array ('create _ time', NOW_TIME, self: MODEL_INSERT ),
);
/**
* File Upload
* @ Param array $ list of files to be uploaded (usually the $ _ FILES array)
* @ Param array $ setting file upload Configuration
* @ Param string $ driver upload driver name
* @ Param array $ config upload driver Configuration
* @ Return the information after the array file is uploaded successfully
*/
Public function upload ($ files, $ setting, $ driver = 'local', $ config = null ){
/* Upload a file */

$ Upload = new Upload ($ setting, $ driver, $ config );
$ Info = $ Upload-> upload ($ files );
If ($ info) {// The file is uploaded successfully, recording the File Information

Return $ info; // The object is successfully uploaded.
} Else {
$ This-> error = $ Upload-> getError ();
Return false;
}
}
/**
* Download a specified object
* @ Param number $ root directory
* @ Param integer $ id file ID
* @ Param string $ args callback function parameters
* @ Return boolean false-download failed; otherwise, the downloaded file is output.
*/
Public function download ($ root, $ id, $ callback = null, $ args = null ){
/* Get the downloaded file information */
$ File = $ this-> find ($ id );
If (! $ File ){
$ This-> error = 'this file does not exist! ';
Return false;
}
/* Download the object */
Switch ($ file ['location']) {
Case 0: // download a local file
$ File ['rootpath'] = $ root;
Return $ this-> downLocalFile ($ file, $ callback, $ args );
Case 1: // TODO: Download a remote FTP File
Break;
Default:
$ This-> error = 'unsupported file storage type! ';
Return false;
}
}
/**
* Checks whether the currently uploaded file already exists.
* @ Param array $ file Upload array
* @ Return boolean file information, false-this file does not exist
*/
Public function isFile ($ file ){
If (empty ($ file ['md5']) {
Throw new \ Exception ('missing parameter: md5 ');
}
/* Search for files */
$ Map = array ('md5' => $ file ['md5'], 'sha1' => $ file ['sha1'],);
Return $ this-> field (true)-> where ($ map)-> find ();
}
/**
* Download a local file
* @ Param array $ array of file Information
* @ Param callable $ callback: the callback function for downloading. It is generally used to increase the number of downloads.
* @ Param string $ args callback function parameters
* @ Return boolean if download fails, false is returned.
*/
Private function downLocalFile ($ file, $ callback = null, $ args = null ){
If (is_file ($ file ['rootpath']. $ file ['savepath']. $ file ['savename']) {
/* Call the callback function to add downloads */
Is_callable ($ callback) & call_user_func ($ callback, $ args );
/* Execute download * // TODO: resumable upload of large files
Header ("Content-Description: File Transfer ");
Header ('content-type: '. $ file ['type']);
Header ('content-Length: '. $ file ['SIZE']);
If (preg_match ('/MSIE/', $ _ SERVER ['HTTP _ USER_AGENT ']) {// for IE
Header ('content-Disposition: attachment; filename = "'. rawurlencode ($ file ['name']).'" ');
} Else {
Header ('content-Disposition: attachment; filename = "'. $ file ['name'].'" ');
}
Readfile ($ file ['rootpath']. $ file ['savepath']. $ file ['savename']);
Exit;
} Else {
$ This-> error = 'the file has been deleted! ';
Return false;
}
}
/**
* Clear data that exists in the database but does not exist locally.
* @ Param $ data
*/
Public function removeTrash ($ data ){
// $ This-> where (array ('id' => $ data ['id'],)-> delete ();
}
}

4. modify the code for calling the upload class


Public function ImgUpload ()
{
// $ This-> error ("no file! ");
// TODO: User Logon Detection
/* Call the File Upload Component to upload a file */
$ Picture = D ('picture ');
$ Pic_driver = C ('picture _ UPLOAD_DRIVER ');
$ Info = $ Picture-> upload (
$ _ FILES,
C ('picture _ upload '),
C ('picture _ UPLOAD_DRIVER '),
C ("UPLOAD _ {$ pic_driver} _ CONFIG ")
); // TODO: upload to the remote server
/* Record image information */
If ($ info ){
/* Return JSON data */
Echo json_encode ($ info );

} Else {
Echo json_encode ($ info );
}
}

5. Use ajaxfileupload on the client to call the php Method


// Upload an image
$ (Document). on ('change', '# upfile', function (){
$. AjaxFileUpload ({
Url: '{: U ("Company/ImgUpload ")}',
Secureuri: false,
FileElementId: 'upfile ',
DataType: 'json ',
Type: 'post ',
Data: {fileElementId: 'upfile '},
Success: function (data ){

$ ('# Showimg'). attr ('src', data. upfile. url );
$ ('# Imageurl'). val (data. upfile. url );
}
})
})
It is best to use the json data type for transmission.

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.