Fine Uploader File Upload component application Introduction _php skills

Source: Internet
Author: User
Tags function definition 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 upload files. At the same time in the browser directly supporting the file drag [browser version of the requirements of the same version of IE must be 9 or higher IE10]. Provides a unified user experience in different browsers. This component basically covers all the current mainstream browsers. There are no Third-party component dependencies at the same time. Quite clear. has been overwritten on the server side to support the The upload details are similar to the restrictions on file size, file type, number of file uploads, etc. through the unified interface to expose options to operate.

See GitHub on fine Uploader according to the official statement. Fine Uploader predecessor is Ajax Upload. The new version Fine uploader mainly adds some new features. From the 1.0 release of the Realse note. The biggest difference is that. Fine Uploder is not based on the jquery component. Some of the details are also more tightly consolidated. Similar return values are all unified in JSON format. For background server operations and front-end DOM objects some operations code is all set in the JS script file. This integration makes the fine The uploader component is very simple to use. Only need to add a Css+javascript file to achieve file upload. Greatly simplifies user reference and operation component difficulty.

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

You can see in the root directory that client client calls require the use of files. The server directory is the corresponding version of the different language PERL/PHP/ASP.NET[VB]. The test directory contains a full local sample Demo. Available for reference.
How to quickly build a simple demo? In fact, the official on the Basic-demo-page has given a simple demonstration. It is built here based on the bootstrap approach.
First create a new HTML blank page. Name fineuploderdemo.html. Add the following CSS references as follows:

Copy Code code as follows:

<link href= "Static/css/fineuploader.css" rel= "stylesheet" >
<link href= "Static/css/bootstrap.min.css" rel= "stylesheet" >

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

<script src= "Static/script/fineupload/header.js" ></script>
<script src= "Static/script/fineupload/util.js" ></script>
<script src= "Static/script/fineupload/button.js" ></script>
<script src= "Static/script/fineupload/handler.base.js" ></script>
<script src= "Static/script/fineupload/handler.form.js" ></script>
<script src= "Static/script/fineupload/handler.xhr.js" ></script>
<script src= "Static/script/fineupload/uploader.basic.js" ></script>
<script src= "Static/script/fineupload/dnd.js" ></script>
<script src= "Static/script/fineupload/uploader.js" ></script>

Where Uploder.js and uploder.basic.js are all the front-end upload features are implemented in this script. Must be referenced.
Add the processing and loading in the client directory at the same time the dynamic picture required for the two progress display. The picture is called in the Fineuploder.css file.
Add the following code to the body:
Copy Code code as follows:

<div id= "Bootstrapped-fine-uploader" ></div>
function Createuploader () {
var uploader = new QQ. Fineuploader ({
Element:document.getElementById (' Bootstrapped-fine-uploader '),
Request: {
Endpoint: ' Server/handlerfunction '
Text: {
Uploadbutton: ' <i class= ' icon-upload icon-white ' ></i> click me now and upload a product image '
' <div class= ' qq-uploader span12 ' > ' +
' <pre class= ' qq-upload-drop-area span12 ' ><span>{dragZoneText}</span></pre> ' +
"<div class=" Qq-upload-button btn btn-success "style=" Width:auto; >{uploadButtonText}</div> ' +
' <span class= ' qq-drop-processing ' ><span>{dropProcessingText}</span> ' +
' <span class= ' qq-drop-processing-spinner ' ></span></span> ' +
"<ul class=" qq-upload-list "style=" margin-top:10px; Text-align:center; " ></ul> ' +
' </div> ',
Classes: {
Success: ' Alert Alert-success ',
Fail: ' Alert Alert-error '

Window.onload = Createuploader;

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

View JS build Qq.fineuploader object creation process. First Specify fine The DOM element of the uploader plug-in. Fetch the operation through the DOM. Request is the corresponding server-side implementation file path. It is recommended not to build server-side processing on your own. Instead, the official file can be used to modify the implementation of the document. Template is the corresponding upload file add content template or modify it. is a Boolean value. To control whether to print fine uploader debug information using the browser's console, default to 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, etc. add format as follows:
Copy Code code as follows:

Allowedextensions: [' jpeg ', ' jpg ', ' gif ', ' PNG '],
sizelimit:204800/mb = * 1024 bytes
allowedextensions controls the suffix format array of uploaded files.
SizeLimit the maximum size of the uploaded file, in bytes. Browsers do not necessarily support this setting. can also be set on the server side.
Minsizelimit: The lower limit of the file size to upload, in bytes. Ditto some browsers have an adapter problem. It is recommended that the service-side settings be unified.
In addition, for QQ. Fineuploder the entire process of performing an upload operation. Five clients are defined to handle additional operations. You can set the definition under callback parameters:
Onsubmit:function (ID, fileName) {
$messages. Append (' <div id= "file-' + ID + '" class= "alert" style= "margin:20px 0 0" ></div> ");
Onupload:function (ID, fileName) {
$ (' #file-' + ID). addclass (' Alert-info ')
. html (' ' +
' Initializing ' +
' "' + FileName + '");

OnSubmit Event: File started committing. The calling parameter format is as follows: Onsubmit:function (Id,filename) {}.
Onupload Event: File started uploading. The calling 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 calling parameter format is as follows: Oncancel:function (Id,filename) {}.
For example, the last 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 the event parameter description is as follows:
Id: Represents the first few files to begin uploading. The Fine uploder definition is the default starting from 0 count.
FileName: The filename of the uploaded file.
Loaded: Indicates the size of the server-side data already uploaded [byte].
Total: The size of the file that needs to be uploaded.
Responsejson: JSON-formatted data to be returned after an upload operation is completed. Deserialize the object through jquery. It contains a issuccess attribute to determine if the upload was successful.
If you want to pass the data to the server at the upload process, you can control it by using the following parameters:
Params: Used to deliver data to the server side. Note that params uses Key-value array storage. Post to the server. The general pass parameter format is as follows:
Copy Code code as follows:

Argument1: "Value1",
Argument2: "value2"

Ok. At this time basic about fine uploader client initialization and control operation options are basically complete. When we need to upload the operation. If Isauto=false can pass already defined QQ. The Fineuploader object's Uploadstorefiles () method triggers the upload operation manually:
Copy Code code 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 Code code as follows:

Endpoint: ' Server/handlerfunction '

At this point we need to specify the PHP file to process the file upload in endpoint [this is Phpdemo]. About the server side if you don't have the 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 is modified as follows:
Copy Code code as follows:

Endpoint: ' controller/php.php '

Open php.php found in the file header description of the file used simultaneously in the file definition three classes are used to handle XMLHttpRequest, Formpost, basicpost file server-side processing separately. In the note 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 () and 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 method has been described in detail. Add the following PHP code to simply complete server-side processing:
Copy Code code 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 cap is defined as 10M. Note that the Phpinfo () method is used to output the current PHP environment configuration. The default upload file size is 2M by default. If you need to upload bigger then modify the php.ini file configuration parameters no more.
Uploder is the initialization of QQ. Fileuploder object. and load the configuration.

The Fineuploder call handles the upload function. and delivers the server-side store upload file storage path.
Echo wants server-side output to be uploaded. You must. Otherwise, the client does not receive the specified Responsejason parameter to determine the status after the upload.
In a further look at how the server side handles uploads, find the Handleupload function definition.
Copy Code code 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);
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 is invoked. It is necessary to note that the URL that is passed is stored as absolute when the path is needed. So you need to do a bit of formatting on the incoming road:
$uploadDirectory = $_server[' Document_root ']. " DS ". $uploadDirectory;
The judgment that the is_writeable file is writable. Personally, I don't think it's detailed enough. Is_writeable primarily determines whether a file or directory exists. and can write to return true. So it's personal to suggest that you add a file before is_writable. This makes it easier to determine the server-side file error in the client:
Copy Code code 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. The processing function makes four judgements respectively. The number of uploaded files, file upload size, file upload size exceeds the upper limit, and the upload process. If we want to upload the same file on the server multiple times. Found fine The Uploder treatment is. It's not an override. Instead, rewrite the name from 10-99 random digits. And save it to the directory. When the file is saved, the server side returns a JSON data containing issuccess to specify whether the upload operation is successful. The issuccess parameter is used as the client to determine the unique parameter at this time.

In the upload operation process many letters appear "increase post_max_size and upload_max_filesize to 10M" error, In fact, to address this problem. The main upload file configuration is more than the default 2M of PHP environment. You need to change the value of Post_max_size and upload_max_filesize two to 10M in the php.ini file, Then restart Apache. or refer to the PHP website to modify the php.ini configuration file for configuration instructions.
The entire fine uploader configuration process has been completed. Click Select File. The following effects:

Prompt upload success. Of course, please refer to the official demo demo. Above from the fine uploader source point of view to analyze its implementation principle.

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