


Fine Uploader file upload component application introduction_PHP tutorial
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:
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:
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:
<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"> Click me now and upload a product image' <BR>}, <BR>template: <BR>'<div class="qq-uploader span12">' + <BR>'<pre class='brush:php;toolbar:false;'><span>{dragZoneText}</span></pre>' + <BR>'<div class="qq-upload-button btn btn-success" style="width: auto;">{uploadButtonText}</script>
'{dropProcessingText}'+
'' +
'
'',
classes: {
success: 'alert alert-success',
fail: 'alert alert-error'
},
debug: true
});
}
window.onload = createUploader;
这是基于Bootstrap实现对Fine Uploader最简单的前端调用.前端一般需要做两件事A:添加Css+Js文件引用.B:在Js中实例化qq.FineUploder对象.运行效果如下:

查看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 ' +
'“' + 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:
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:
$('#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:
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:
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:
$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. .
/**
* 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:
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:

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.

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version
Chinese version, very easy to use

SublimeText3 Linux new version
SublimeText3 Linux latest version

Zend Studio 13.0.1
Powerful PHP integrated development environment