Fine Uploader file upload component application introduction_PHP tutorial

WBOY
Release: 2016-07-21 15:13:46
Original
1289 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:
2013-01-04_162943
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 code The 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 code The 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:
Copy the code The code is as follows:


<script> <br>function createUploader() { <br>var uploader = new qq.FineUploader({ <br>element: document.getElementById('bootstrapped-fine-uploader'), <br>request: { <br>endpoint: 'server/handlerfunction' <br>}, <br>text: { <br>uploadButton: '<i class="icon-upload icon-white"></i> Click me now and upload a product image' <br>}, <br>template: <br>'<div class="qq-uploader span12">' + <br>'<pre class="qq-upload-drop-area span12">&lt;span&gt;{dragZoneText}&lt;/span&gt;</pre>' + <br>'<div class="qq-upload-button btn btn-success" style="width: auto;">{uploadButtonText}</div>' + <br>'<span class="qq-drop-processing"><span>{dropProcessingText}</span>'+ <br>'<span class="qq-drop-processing-spinner"></span></span>' + <br>'<ul class="qq-upload-list" style="margin-top: 10px; text-align: center;"></ul>' + <br>'</div>', <br>classes: { <br>success: 'alert alert-success', <br>fail: 'alert alert-error' <br>}, <br>debug: true <br>}); <br>} <br><br>window.onload = createUploader; <br></script>

这是基于Bootstrap实现对Fine Uploader最简单的前端调用.前端一般需要做两件事A:添加Css+Js文件引用.B:在Js中实例化qq.FineUploder对象.运行效果如下:
2013-01-04_170433 
查看JS构建qq.Fineuploader对象创建过程.首先指定Fine Uploader插件的Dom元素.通过Dom获取操作.request则是对应服务器端实现文件路径.在这建议不要自己构建服务器端处理.而是直接采用官方提供的实现文件修改即可.template则是对应上传文件添加内容模版也可以自己修改.debug是一个布尔值.用来控制是否使用浏览器的控制台打印Fine Uploader的调试信息,默认为false.
qq.FineUploader对象还有如下控制参数:
validation:该参数一般用来在执行上传文件操作前.在客户端做一些验证.验证操作包含文件格式.文件大小.等添加格式如下:
复制代码 代码如下:

validation:
{
allowedExtensions: ['jpeg', 'jpg', 'gif', 'png'],
sizeLimit: 204800 // 200 kB = 200 * 1024 bytes
}
allowedExtensions控制上传文件的后缀格式数组.
sizeLimit上传文件大小的上限,单位为byte的数值.浏览器不一定支持本设置.也可以在服务器端里设置.
minSizeLimit:上传文件大小的下限,单位为byte的数值.同上有些浏览器存在适配问题.建议统一在服务端设置.
另外针对qq.FineUploder对象在执行上传操作整个过程.定义了五个客户端可控做额外操作的事件.可以再callback参数下设置定义:
callbacks:
{
onSubmit: function(id, fileName) {
$messages.append('
');
},
onUpload: function(id, fileName) {
$('#file-' + id).addClass('alert-info')
.html('Initializing. Please hold. ' +
'Initializing ' +
'“' + fileName + '”');
}
}

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:
Copy code The code is as follows:

params:
{
argument1: "value1",
argument2: "value2"
},

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:
Copy code The code is as follows:

$('#triggerUpload').click(function() {
uploader2.uploadStoredFiles();
});

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 code The 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 code The 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:
Copy code The 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 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 code The 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:
Copy code The code is as follows:

if (!file_exists($uploadDirectory)) {
return array('error' => "Server error. Upload directory dones't exist.");
}

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:
2013-01-04_191128
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.

www.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...
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template