Fine Uploader File Upload Component application Introduction _php Tutorial

Source: Internet
Author: User
Tags php website blank page
Recently, you need to implement file uploads when working with background data. Consider the use of fine Uploader for browser adaptation. Fine Uploader uses Ajax to implement file uploads. Also support file drag and drop directly in the browser [the browser version is required to be similar to the IE version must be 9 or higher IE10]. Provide a unified user experience across browsers. This component basically covers all current mainstream browsers. There is no third-party component dependent. Quite clear. Asp.net/coldfusion/java/node.js/perl/php/python is supported on the server side. Similar to upload details such as limit file size, file type, number of file uploads, etc. through the unified interface to expose the option mode operation.

See fine Uploader on GitHub according to the official statement. Fine Uploader was formerly Ajax Upload. New version Fine uploader mainly add some new features. From the 1.0 release of the Realse note. The biggest difference between the two is. Fine Uploder is not based on jquery components. And some of the details are more uniform. The return values are all unified in JSON format. Some operations on background server operations and front-end DOM objects code is all set in the JS script file. This integration makes the fine Uploader components are very simple to use. Just add a css+javascript file to upload the file. Greatly simplifies user reference and operation of component difficulty.

Fine Uploader features are as follows:
Fine Uploader Features:
A: Support file upload progress display.
B: File drag and drop browser upload method
C:ajax page is not refreshed.
D: Multiple file uploads.
F: Cross-browser.
E: Cross-background server-side language.
On the git hub fine uploader Download the packaging source code, in PHP Designer 8 open Its source code can see its source structure as follows:

In the root directory, you can see that the client call needs to use the file. The server directory is implemented for versions that correspond to different languages PERL/PHP/ASP.NET[VB]. The test directory contains a complete local sample Demo. Available for reference.
How to quickly build a simple demo? In fact, the official has given a simple demonstration on basic-demo-page. This is based on the bootstrap approach.
First create a new HTML blank page. Name fineuploderdemo.html. Add the following CSS reference as follows:
Copy CodeThe code is as follows:



These two files must be referenced by the. FINEUPLOADER.CSS is the corresponding download fine uploder source Client directory. FINEUPLODER.CSS provides the CSS style required in the JS script, mainly including the style of the button, The style of the progress display and the style of the upload result. The add JavaScript file is referenced as follows:
Copy CodeThe code is as follows:










Where Uploder.js and Uploder.basic.js are the frontend all uploads are implemented in the script. Must be referenced.
Add the dynamic images required for the processing and loading two progress display in the client directory at the same time. The picture is called in the Fineuploder.css file.
Add the following code to the body:
Copy CodeThe code is as follows:



This is the simplest front-end invocation of the fine uploader based on the bootstrap implementation. The front end usually needs to do two things a: Add a Css+js file reference. B: Instantiate the Qq.fineuploder object in JS. The effect of the operation is as follows:

View JS build Qq.fineuploader object creation process. First Specify fine Uploader the DOM element of the plug-in. Gets the operation through the DOM. The request is the corresponding server-side implementation file path. It is recommended that you do not build server-side processing on your own. Instead, use the officially provided implementation file to modify it. Template is the corresponding upload file to add content template can also be modified. is a Boolean value. Used to control whether to use the browser's console to print fine uploader debug information, the default is False.
QQ. The Fineuploader object also has the following control parameters:
Validation: This parameter is typically used before performing an upload file operation. Do some validation on the client. The validation action contains the file format. File size. Add the following format as follows:
Copy CodeThe code is as follows:
Validation
{
Allowedextensions: [' jpeg ', ' jpg ', ' gif ', ' PNG '],
sizelimit:204800//KB = $ * 1024x768 bytes
}
Allowedextensions controls the array of suffix formats for the uploaded file.
SizeLimit the maximum size of the uploaded file, in bytes. The browser does not necessarily support this setting. It can also be set on the server side.
Minsizelimit: The lower limit of the size of the uploaded file, in bytes. There are some browsers that have an adaptation problem. It is recommended that the server be set up on a uniform.
Also for QQ. The Fineuploder object performs the entire process of the upload operation. Defines five events that the client can control to perform additional operations. You can set the definition again under the callback parameter:
Callbacks:
{
Onsubmit:function (ID, fileName) {
$messages. Append (");
},
Onupload:function (ID, fileName) {
$ (' #file-' + ID). addclass (' Alert-info ')
. html (' +
' Initializing ' +
"' + fileName + '" ');
}
}

OnSubmit Event: File is submitted. The calling parameter format is as follows: Onsubmit:function (Id,filename) {}.
Onupload Event: File started uploading. The invocation parameter format is as follows: Onupload:function (ID, fileName) {}.
OnProgress event: File is being uploaded. The calling parameter format is as follows: Onprogress:function (Id,filename,loaded,total) {}.
OnComplete Event: File upload succeeded. The calling parameter format is as follows: Oncomplete:function (Id,filename,responsejson) {}.
OnCancel Event: Cancel file upload. The invocation parameter format is as follows: Oncancel:function (Id,filename) {}.
The above five events basically cover all the processes in the entire upload file operation. The client can operate completely in an open form. About the call as above event parameters are described below:
Id: Represents the first file to begin uploading. The Fine uploder definition is the default count starting from 0.
FileName: The name of the file to upload.
Loaded: Indicates the size of data that has been uploaded to the server side [byte].
Total: The size of the file that needs to be uploaded.
Responsejson: The JSON-formatted data that is used to return after the upload operation is complete. Deserializes the object through jquery. It contains a issuccess attribute to determine whether the upload was successful.
If you want to pass the data to the server side during the upload process, you can control it with the following parameters:
Params: Used to pass data to the server. Note that the params is stored in an array of key-value. Sent to the server side by post. The general pass-through parameter format is as follows:
Copy CodeThe code is as follows:
Params:
{
Argument1: "Value1",
Argument2: "value2"
},

Ok. At this point the basic about fine uploader client initialization and control operation options are basically complete. When we need to upload an operation. If the isauto=false can be defined by the QQ. The Fineuploader object's Uploadstorefiles () mode manually triggers the upload operation:
Copy CodeThe code is as follows:
$ (' #triggerUpload '). Click (function () {
Uploader2.uploadstoredfiles ();
});

If we click Upload at this point, we will find that the upload failed. Because there is no processing on the upload server side:
Copy CodeThe code is as follows:
Request
{
Endpoint: ' Server/handlerfunction '
},

At this point we need to specify the PHP file to process the file upload in endpoint [here is Phpdemo]. About the server side if you do not have a mature processing module. It is recommended that you use the official server directory. Here I use the PHP environment when the php.php file is selected. The corresponding client modifications are as follows:
Copy CodeThe code is as follows:
Request
{
Endpoint: ' controller/php.php '
}

Open php.php found in the file header description of the file used at the same time in the file definition three classes used to handle XMLHttpRequest, Formpost, basicpost way File server-side processing. In the comments at the top of the file:
/****************************************
Example of how to use this uploader class ...
Can uncomment the following lines (minus the require) to use
Hese as your defaults.

List of valid extensions, ex. Array ("JPEG", "xml", "BMP")
$allowedExtensions = Array ();
Max file size in bytes
$sizeLimit = 10 * 1024 * 1024;
The input name set in the JavaScript
$inputName = ' Qqfile '

Require (' valums-file-uploader/server/php.php ');
$uploader = new Qqfileuploader ($allowedExtensions, $sizeLimit, $inputName);

Call Handleupload () with the name of the folder, relative to PHP ' s GETCWD ()
$result = $uploader->handleupload (' uploads/');

To pass data through IFRAME you'll need to encode all HTML tags
Header ("Content-type:text/plain");
Echo Htmlspecialchars (Json_encode ($result), ent_noquotes);

/******************************************/
The following class invocation methods are described in detail. Add the following PHP code to simply complete server-side processing:
Copy CodeThe code is as follows:
$allowedExtensions = Array ("JPEG", "JPG", "BMP", "PNG");
$sizeLimit = 10 * 1024 * 1024;
$uploader = new Qqfileuploader ($allowedExtensions, $sizeLimit);
$result = $uploader->handleupload (' uploads/'); Folder for uploaded files
Echo Htmlspecialchars (Json_encode ($result), ent_noquotes);

AllowExtensions defines the format in which files are allowed to be uploaded.
The SizeLimit upper limit is defined as 10M. Note that the Phpinfo () method is used to output the current PHP environment configuration. By default, the default upload file size is 2M. If you need to upload larger then modify the php.ini file configuration parameters here no longer repeat.
Uploder is the initialization of QQ. The Fileuploder object. and loads the configuration.

The Fineuploder call handles the upload function. and pass the server-side store upload file storage path.
Echo wants the server-side output to upload the results. Otherwise, the client cannot accept the specified Responsejason parameter to determine the post-upload state.
Take a closer look at how the server-side handles uploads to find the Handleupload function definition.
Copy CodeThe code is as follows:
/**
* Handle the uploaded file
* @param string $uploadDirectory
* @param string $replaceOldFile =true
* @returns Array (' success ' =>true) or array (' ERROR ' = ' error message ')
*/
function Handleupload ($uploadDirectory, $replaceOldFile = FALSE) {
if (!is_writable ($uploadDirectory)) {
Return Array (' error ' = = ' Server error. Upload directory isn ' t writable. ");
}

if (! $this->file) {
Return Array (' ERROR ' = ' No. ' files were uploaded. ');
}

$size = $this->file->getsize ();

if ($size = = 0) {
Return Array (' ERROR ' = ' File is empty ');
}

if ($size > $this->sizelimit) {
Return Array (' ERROR ' = ' File is too large ');
}

$pathinfo = PathInfo ($this->file->getname ());
$filename = $pathinfo [' filename '];
$filename = MD5 (uniqid ());
$ext = @ $pathinfo [' extension '];//hide notices if extension is empty

if ($this->allowedextensions &&!in_array (Strtolower ($ext), $this->allowedextensions)) {
$these = Implode (', ', $this->allowedextensions);
The return array (' ERROR ' = ' File has a invalid extension, it should be one of '. $these. '.');
}

$ext = ($ext = = ")? $ext: '. '. $ext;

if (! $replaceOldFile) {
Don ' t overwrite previous files that were uploaded
while (File_exists ($uploadDirectory. Directory_separator. $filename. $ext)) {
$filename. = Rand (10, 99);
}
}

$this->uploadname = $filename. $ext;

if ($this->file->save ($uploadDirectory. Directory_separator. $filename. $ext)) {
Return Array (' success ' =>true);
} else {
Return Array (' error ' = ' = ' Could not ' save uploaded file '.
' The upload was cancelled, or server error encountered ');
}

}

When this handler function is called. It is important to note that the URL that is passed to the storage path needs to be absolute. So we need to do a bit of formatting for the incoming route:
$uploadDirectory = $_server[' Document_root '). " DS ". $uploadDirectory;
The is_writeable file is not writable. I personally think it's not detailed enough. Is_writeable primarily determines whether a file or directory exists. and can be written to return true. Therefore, it is recommended to add a file before is_writable. This makes it easier to determine the server-side file error in the client's case:
Copy CodeThe code is as follows:
if (!file_exists ($uploadDirectory)) {
Return Array (' error ' = = ' Server error. Upload directory dones ' t exist. ");
}

Before you save the file operation. You can see that. processing functions were judged four times. The number of uploaded files, the size of the file upload, the file upload size exceeded the upper limit, and the upload process. If we want to upload the same file on the server multiple times. Discover fine The Uploder process is. It is not a rewrite. Instead, the file is named by a 10-99 random number rewrite. and saved to the directory. When the file is saved successfully. You want the server to return a JSON data that contains issuccess to specify whether the upload operation was successful. The issuccess parameter acts as the client to determine the unique parameters at this time.

Many "increase post_max_size and upload_max_filesize to 10M" errors occurred during the upload operation, In fact, for this problem. The main upload file configuration exceeds the default 2M of the PHP environment. You need to change the value of Post_max_size and upload_max_filesize two to above 10M in the php.ini file. Then restart Apache. or refer to the PHP website for configuration instructions to modify the php.ini configuration file.
At this point the entire fine uploader configuration process has been completed. Click to select a file. The effect is as follows:

Prompt for upload success. Of course, please refer to the official demo demo. The implementation principle is analyzed from fine uploader source angle.

http://www.bkjia.com/PHPjc/326398.html www.bkjia.com true http://www.bkjia.com/PHPjc/326398.html techarticle recently, you need to implement file uploads when working with background data. Consider the use of fine Uploader for browser adaptation. Fine Uploader uses Ajax to implement file uploads. While in the browser straight ...

  • 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.