Introduction to the Fine Uploader File Upload Component in asp.net

Source: Internet
Author: User

You need to upload files when processing background data recently. fine Uploader is used for browser adaptation. fine Uploader uses ajax to upload files. at the same time, you can drag and drop files in the browser. [The requirements for browser versions are similar to IE versions which must be 9 or later.] provide unified user experience in different browsers. this component basically covers all mainstream browsers. no third-party component dependency. pretty Clear. the server already supports ASP. NET/ColdFusion/Java/Node. js/Perl/PHP/Python. the upload details are similar to restrictions on the file size, file type, and number of files to be uploaded.

Foot home http://www.jb51.net/codes/70040.html

See Fine Uploader on Github according to the official statement. fine Uploader is formerly called Ajax Upload. the new version of Fine Uploader mainly adds some new features. from the Realse Note released in Version 1.0. the biggest difference between the two is. fine Uploder is not based on Jquery components. some details are handled more uniformly and strictly. similar return values are all in Json format. the operation Code for background server operations and front-end Dom objects is all concentrated in the Js Script file. this integration makes the Fine Uploader component easy to use. you only need to add a CSS + JavaScript file to upload the file. this greatly simplifies the difficulty of referencing and operating components.

Fine Uploader has the following features:

Fine Uploader Features:
A: displays the File Upload progress.
B: How to upload files by dragging the browser
C: The Ajax page is refreshing.
D: upload multiple files.
F: cross-browser.
E: Cross-background server language.
Download and package the source code from 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 that the file is required for Client calls. the Server directory is implemented in versions such as Perl, Php, and Asp.net [VB] in different languages. the test directory contains a complete local Sample Demo. for reference.

How to quickly build a simple Demo? In fact, the official Basic-Demo-Page has provided a simple demonstration, which is built based on the Bootstrap method.
First, create an HTML blank page. Name fineuploderdemo.html. Add the following CSS Reference:
Copy codeThe Code is as follows:
<Link href = "static/css/fineuploader.css" rel = "stylesheet">
<Link href = "static/css/bootstrap.min.css" rel = "stylesheet">

When these two files are used, the. fineuploader.css file is the CSS style required for downloading the Fine definition file. It mainly includes the style of the button, the style of the Progress display, and the style of the upload result. Add a reference to the JavaScript file as follows:
Copy codeThe Code is 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>

Among them, uploder. js and uploder. basic. js are implemented by all the frontend upload functions in this script. They must be referenced.
At the same time, the two Progress sheets processingand loadingin the clientdirectory show the dynamic images. The images are all called in the fineuploder.css file.
Add the following Code to the body:
Copy codeThe Code is as follows:
<Div id = "bootstrapped-fine-uploader"> </div>
<Script>
Function createUploader (){
Var uploader = new qq. FineUploader ({
Element: document. getElementById ('bootstrapped-fine-upload '),
Request :{
Endpoint: 'server/handlerfunction'
},
Text :{
UploadButton: '<I class = "icon-upload icon-white"> </I> Click me now and upload a product image'
},
Template:
'<Div class = "qq-uploader span12">' +
'<Pre class = "qq-upload-drop-area span12"> <span >{ dragZoneText} </span> </pre>' +
'<Div class = "qq-upload-button btn-success" style = "width: auto;" >{uploadbuttontext} </div>' +
'<Span class = "qq-drop-processing"> <span >{ dropProcessingText} </span>' +
'<Span class = "qq-drop-processing-spinner"> </span>' +
'<Ul class = "qq-upload-list" style = "margin-top: 10px; text-align: center;"> </ul>' +
'</Div> ',
Classes :{
Success: 'alert alert-success ',
Fail: 'alert alert-error'
},
Debug: true
});
}
Window. onload = createUploader;
</Script>

This is the simplest frontend call to Fine Uploader Based on Bootstrap. the front end usually needs to do two things A: Add Css + Js file reference. b: instantiate qq in Js. fineUploder object. the running effect is as follows:

View JS build qq. the Fineuploader object creation process. first, specify the Dom element of the Fine Uploader plug-in. use Dom to retrieve data. the request is the file path of the corresponding server. we recommend that you do not create a server for processing. instead, you can directly modify the file using the official file. you can modify the template by yourself. debug is a Boolean value. used to control whether to use the browser console to print Fine Uploader debugging information. The default value is false.
The qq. FineUploader object also has the following control parameters:
Validation: this parameter is generally used to perform some verification on the client before performing the file upload operation. The verification operation includes the file format, file size, and other adding formats as follows:
Copy codeThe Code is as follows:
Validation:
{
AllowedExtensions: ['jpeg ', 'jpg', 'gif', 'png '],
SizeLimit: 204800 // 200 kB = 200*1024 bytes
}

AllowedExtensions controls the suffix format array of the uploaded file.
The maximum size of the sizeLimit file to be uploaded. The unit is a byte value. The browser does not necessarily support this setting. You can also set it on the server.
MinSizeLimit: the lower limit of the size of the uploaded file. The unit is the byte value. The adaptation problem exists in some browsers. We recommend that you set it on the server.
In addition, for the whole process of uploading qq. FineUploder objects, five clients are defined to control additional operations. You can set the definition under the callback parameter:
Copy codeThe Code is as follows:
Callbacks:
{
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: the file is 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: cancels 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 file upload operation. They can be operated on the client in an open form. The preceding event parameters are described as follows:
Id: indicates the objects to be uploaded. Fine Uploder defines the default count starting from 0.
FileName: name of the file to be uploaded.
Loaded: indicates the size of data uploaded to the server [byte].
Total: the size of the file to be uploaded.
ResponseJSON: Json-format data returned after the upload operation is complete. The object is deserialized using Jquery. It contains an IsSuccess attribute to determine whether the upload is successful.
If you want to transmit data to the server during the upload process, you can use the following parameter control:
Params: used to transmit data to the server. Note that params uses the key-value array for storage. It is sent to the server using the Post method. Generally, the parameter format is as follows:
Copy codeThe 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 the upload operation. if IsAuto = false, you can use the defined qq. the uploadStoreFiles () method of the FineUploader object manually triggers the upload operation:
Copy codeThe Code is as follows:
$ ('# TriggerUpload'). click (function (){
Uploader2.uploadStoredFiles ();
});

If you click upload at this time, you will find that the upload fails because you have not processed the upload Server:
Copy codeThe Code is as follows:
Request:
{
Endpoint: 'server/handlerfunction'
},

In this case, you need to specify the PHP file to process file uploads at the EndPoint [phpdemo]. if you have no mature processing module on the server side. we recommend that you use the official Server directory. here, php is selected when I use the php environment. PHP file. the corresponding client is modified as follows:
Copy codeThe Code is as follows:
Request:
{
Endpoint: 'controller/php. php'
}

Open php. php and you will find that in the file header, it indicates that the file uses three classes defined in the file to process the file server in the XMLHttpRequest, FormPost, and BasicPost methods respectively. In the file top comment:
Copy codeThe Code is as follows:
/*************************************** *
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. You can simply process the server by adding the following Php code:
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 of the file to be uploaded.

The upper limit of sizeLimit is defined as 10 m. note that you must first use Phpinfo () to output the current php environment configuration. generally, the maximum size of the uploaded file is 2 MB by default. modify php if you need to upload larger files. the INI file configuration parameters are not described here.

Uploder initializes the qq. Fileuploder object and loads the configuration.

Fineuploder calls the upload processing function and transmits the file storage path stored on the server side.

Echo: the server outputs the upload result. required. Otherwise, the client cannot accept the specified responseJason parameter to determine the post-upload status.

Let's take a 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' => 'errormessage ')
*/
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 shocould 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 ');
}

}

When calling this processing function, you must note that the stored URL path must be absolute. Therefore, you need to format the input path:
Copy codeThe Code is as follows:
$ UploadDirectory = $ _ SERVER ['document _ root']. "DS". $ uploadDirectory;

Determine whether the is_writeable file is writable. I personally think it is not detailed enough. is_writeable mainly checks whether a file or directory exists. and can be written to return true. therefore, we recommend that you add a file before is_writable to check whether it exists. in this way, it is easier for the client to determine the specific case of file errors on the server:
Copy codeThe 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 functions made four judgments respectively. determine the number of files to be uploaded, the size of the files to be uploaded, whether the size of the files to be uploaded has exceeded the limit, and whether the files are uploaded during the upload process. if we want to upload the same file on the server multiple times. the Fine Uploder processing method is found to be. it is not a rewrite. instead, rename the file from a random number ranging from 10 to 99. and save it to the directory. after the file is saved successfully. then, you want the server to return 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 for this operation.

The error "increase post_max_size and upload_max_filesize to 10M" is frequently sent during the upload operation. the main reason is that the size of the file to be uploaded exceeds the default value of 2 MB in the php environment. in php. in the INI file, change the values of post_max_size and upload_max_filesize to over 10 MB, and restart Apache. or you can refer to the Php official website to modify the php configuration instructions. ini configuration file.

So far, the entire Fine Uploader configuration process has been completed. When you click to select a file, the following results will be displayed:

Indicates that the upload is successful. For more information, see the official demo.The implementation principle is analyzed from the perspective of Fine Uploader source code.

The Reference Links are as follows:
Fine Uploader
Fine Uploader Basic Upload Demo
Git Hub Fine Uploader Document and Code Sample

Related Article

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.