Fine Uploader file upload component application introduction_PHP tutorial
WBOY
Release: 2016-07-21 15:13:46
Original
1207 people have browsed it
Recently, file upload needs to be implemented when processing background data. Considering the browser adaptation, Fine Uploader is used. Fine Uploader uses ajax to upload files. At the same time, it directly supports file drag and drop in the browser [for browsers] The version requirements are similar to IE version 9 or higher [IE10]. It provides a unified user experience in different browsers. This component basically covers all current mainstream browsers. At the same time, it does not rely on any third-party components. It is quite clear. On the server The terminal has covered and supported ASP.NET/ColdFusion/Java/Node.js/Perl/PHP/Python. Upload details such as limiting file size, file type, number of file uploads, etc. are operated through a unified interface and exposed options.
See the Fine Uploader on Github. According to the official statement, the predecessor of Fine Uploader is Ajax Upload. The new version of Fine Uploader mainly adds some new features. Judging from the Realse Note released in version 1.0, the biggest difference between the two is. Fine Uploder is no longer based on Jquery components, and some details are processed more uniformly and strictly. Similar return values are all unified into Json format. Some operation codes for background server operations and front-end Dom objects are all concentrated in Js Script script files. This integration makes the Fine Uploader component It is very simple to use. You only need to add a CSS+JavaScript file to upload files. It greatly simplifies the difficulty of user reference and operation of components.
Fine Uploader features are as follows: Fine Uploader Features : A: Supports file upload progress display. B: File drag and drop browser upload method C: Ajax page without refreshing. D: Multiple file upload. F: Cross-browsing E: Cross-backend server-side language. Download the packaging source code on the Fine Uploader on Git Hub. Open the source code in Php Designer 8 and you can see that the source code structure is as follows:
In the root directory, you can see the files required for Client calls. The Server directory corresponds to different language versions such as Perl/Php/Asp.net[VB]. The test directory contains a complete local Sample Demo. For reference. How to quickly build a simple Demo? In fact, the official has given a simple demonstration on Basic-Demo-Page. It is built based on Bootstrap. First create a new blank Html page. Name it FineUploderDemo.html .Add the following CSS reference as follows:
Copy the codeThe code is as follows:
When these two files The .fineuploader.css that must be referenced corresponds to the .fineuploder.css in the Client directory of the downloaded Fine Uploder source code. It provides the CSS styles 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. Add JavaScript files Quote as follows:
Copy codeThe code is as follows:
Uploder.js and uploader.basic.js are all the upload functions of the front end All are implemented in this script. They must be quoted.
At the same time, add the two dynamic pictures required for progress display of processing and loading in the client directory. The pictures are called in the fineuploder.css file.
Add in the body The following Code:
onSubmit event: The file starts to be submitted. The calling parameter format is as follows: onSubmit:function(id, fileName){}.
onUpload event: The file starts to be uploaded. The calling parameter format is as follows: onUpload: function(id, fileName) { }.
onProgress event: The file is being uploaded. The calling parameter format is as follows: onProgress:function(id,fileName,loaded,total){}.
onComplete event: The file is uploaded successfully. 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){}.
The above five events basically cover the entire upload file operation All processes are completely open and can be operated on the client side. The parameters for calling the above events are as follows:
Id: indicates which file to start uploading. The Fine Uploder definition starts counting from 0 by default.
fileName : The file name of the uploaded file.
loaded: Indicates the size of the data that has been uploaded to the server [byte].
total: The size of the file that needs to be uploaded.
responseJSON: Used to return after the upload operation is completed Data in Json format. The object is deserialized through Jquery. It contains an IsSuccess attribute to determine whether the upload is successful.
If you want to transfer data to the server during the upload process, you can control it through the following parameters:
params: used to transfer data to the server. Note that params is stored in a key-value array. It is sent to the server in Post mode. The general format of passing parameters is as follows:
ok. At this time, the Fine Uploader client initialization and control operation options are basically completed. When we need to upload the operation. If IsAuto=false, we can manually trigger the upload through the uploadStoreFiles() method of the qq.FineUploader object. Operation:
If we click upload at this time, we will find that the upload failed. Because no processing has been done on the upload server:
Copy codeThe code is as follows:
request:
{
endpoint: 'server/handlerfunction'
},
At this time we need to specify the Php file for processing file upload in EndPoint [here is phpdemo]. Regarding the server side, if you do not have a mature processing module, it is still recommended that you use the official Server directory. Here I If the php environment is used, select the php.php file. The corresponding client modification is as follows:
Copy the codeThe code is as follows:
request :
{
endpoint: 'controller/php.php'
}
Open php.php and find in the file header that the file uses three classes defined in the file at the same time Used to handle XMLHttpRequest, FormPost, and BasicPost file server-side processing respectively. In the comments at the top of the file:
/****************************************
Example of how to use this uploader class...
You 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 will need to encode all html tags
header("Content-Type: text/plain");
echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
/******************************************/
The following Class calling method has been described in detail. Add the following Php code to simply Complete server-side processing:
allowExtensions defines the format that allows uploading files.
The upper limit of sizeLimit is defined as 10M. Note that the Phpinfo(); method is first used to output the current PHP environment configuration. Generally, the default maximum size of uploaded files is 2M. If you need To upload a larger file, modify the php.ini file configuration parameters which will not be described here.
uploder initializes the qq.Fileuploder object and loads the configuration.
fineuploder calls the upload processing function and passes the server-side storage upload File storage path.
echo wants the server to output the upload result. It is necessary. Otherwise the client will not be able to accept the specified responseJason parameter to determine the upload status.
Let’s take a closer look at how the server handles the upload and 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);
return array('error' => 'File has an 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 canceled, or server error encountered');
}
}
You need to pay attention when calling this processing function. Yes. The passed URL storage path needs to be absolute. Therefore, you need to format the incoming path:
$uploadDirectory = $_SERVER['DOCUMENT_ROOT']."DS".$uploadDirectory;
For is_writeable determines whether the file is writable. I personally think it is not detailed enough. is_writeable mainly determines whether the file or directory exists. It will return true only if it is writable. Therefore, I personally recommend adding a file before is_writable to see whether it exists. This makes it easier to use on the client. Determine the specific situation of server-side file errors:
Before saving the file, you can see that the processing function made four judgments respectively. It judged the number of uploaded files, the size of the file uploaded, whether the file upload size exceeded the upper limit, and during the upload process. If we have more The next time I want to upload the same file to the server, I found that the Fine Uploder processing method is not to rewrite. Instead, it rewrites and names the file with a random number from 10-99 and saves it to the directory. When the file is saved successfully, I want to The server returns a Json data that contains IsSuccess to specify whether the upload operation is successful. The IsSuccess parameter is used as the only parameter for the client to judge the operation at this time.
During the upload operation, many messages appear "increase post_max_size and upload_max_filesize" to 10M" error, in fact, for this problem, the main reason is that the upload file configuration exceeds the default 2M of the PHP environment. You need to change the values of post_max_size and upload_max_filesize in the php.ini file to more than 10M, and then restart Apache. Or Refer to the Php official website to modify the php.ini configuration file for the configuration instructions.
At this point, the entire Fine Uploader configuration process has been completed. When you click to select the file, the following effect will appear:
Prompt that the upload is successful. Of course, more For more information, please refer to the official demo. As above, the implementation principle is analyzed from the perspective of Fine Uploader source code.
http://www.bkjia.com/PHPjc/326398.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/326398.htmlTechArticleRecently, file upload needs to be implemented when processing background data. Consider using Fine Uploader for browser adaptation. Fine Uploader uses ajax to upload files. At the same time, it can be uploaded directly in the browser...
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn