File Upload Tool jquery upload plugin uploadify

Source: Internet
Author: User

In the daily project, often in the background need to upload pictures and other resource files, before using this component a few times, feel very useful, but every time you use the need to go through a review, so it is better to remember here, after the use of the time to turn over.

His official website is as follows: http://www.uploadify.com/

Plugin: http://www.uploadify.com/download

Description Document: Http://www.uploadify.com/documentation

Before this, the next plug-in using the process, the plug-in is based on jquery, so we need to reference jquery before use, then we can imagine that the role of plug-ins in the foreground to submit data to the background, let us through the background code to save the foreground incoming files. So for example, image preservation, watermark, and other proportional compression does not belong to this category, but I intend to record together.

First, follow the steps below to implement a simple upload function.

1 Create a Web project, named Jqueryuploaddemo, and download the latest version from the official website to unzip and add to the project.

2 Add the Uploadhandler.ashx file to the project to process the upload of the file.

3 Add the UploadFile folder to the project to store the uploaded files.

Depending on the path referenced below, you should be able to know what the specific structure diagram is.

4 default.aspx the code of the HTML page is modified as follows, the file can be considered a public image upload page, by using an IFRAME embedded in the page that needs to be uploaded:

<!DOCTYPEHTML Public"-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >< HTMLxmlns= "http://www.w3.org/1999/xhtml" ><Head> <title>Bulk upload</title> <Linkrel= "Stylesheet"href= "Css/uploadify.css"/> <Scripttype= "Text/javascript"src= "Scripts/jquery-1.4.4.min.js" ></Script> <Scripttype= "Text/javascript"src= "Scripts/jquery.uploadify.min.js" ></Script> <Scripttype= "Text/javascript"src= "Scripts/swfobject.js" ></Script> <Scripttype= "Text/javascript" >$(function() {varSpace ="<%=space%>"; $(' #custom_file_upload '). Uploadify ({' uploader ':' scripts/uploadify.swf ',' script ':' Ashx/upload.ashx ',' Scriptdata ': {"Type":"<%=type%>"},' cancelimg ':' Images/uploadify-cancel.png ',' folder ':'/upload ',' Multi ':<%=Multi%>,' Auto ':false,' Fileext ':' *.jpg;*jpeg;*.gif;*.png;*.mp4 ',' Filedesc ':' picture file (. Jpg. Jpeg. Gif. PNG) ',' Queueid ':' Custom-queue ',' Queuesizelimit ': 10,' Simuploadlimit ': 10,' ButtonText ':' Select File ',//' buttonimg ': '/scripts/uploadify-cancel.png ',' removecompleted ':true,' Onselectonce ':function(Event, data) {                    $(' #status-message '). Text (data.filesselected +' files into the upload queue '); },' Onclearqueue ':function(Event, data) {                    $(' #status-message '). Text (' Please select the file to upload: '); },' OnComplete ':function(Event, Queueid, Fileobj, response, data) {//alert (response.split (' | ') [1]); This gets the URL path of the upload, which is used in the foreground to displayWindow.parent.document.getElementById ('<%=file_id%>'). Value + = Response.split (' | ') [1] + space; },' Onallcomplete ':function(Event, data) {                    $(' #status-message '). Text (data.filesuploaded +' files have been uploaded ');            }            }); $("#Up"). Click (function() {if($("#custom-queue"). html () = ="") {alert ("Please select a file to upload"); }Else{Window.parent.document.getElementById ('<%=file_id%>'). Value =""; $(' #custom_file_upload '). Uploadifyupload (NULL,false);//One pass//$ (' #custom_file_upload '). Uploadifyupload (null, TRUE);//Simultaneous transmission}            }); $("#Clear"). Click (function() {                $(' #custom_file_upload '). Uploadifyclearqueue ();        }); });</Script> <styletype= "Text/css" >Body{font-size:14px;font-family:Microsoft Ya-Black;}#custom-demo. Uploadifyqueueitem{Background-color:#FFFFFF;Border:None;Border-bottom:1px solid #E5E5E5;Font:11px Verdana, Geneva, Sans-serif;Height:20px;Margin-top:0;padding:10px;width:350px; }#custom-demo #custom-queue{Border:1px solid #E5E5E5;Margin-bottom:10px;width:370px; }#custom-demo Object{float: Left; }. Button{float: Right;width:120px;Height:30px;Background-color:#525252;Color:#fff;Border:0;font-size:14px;font-family:Microsoft Ya-Black;cursor:Pointer;Margin-right:10px;_margin-right:7px; }</style></Head><Body> <DivID= "Custom-demo"class= "Demo" > <Divclass= "Demo-box" > <DivID= "Status-message" >Please select a file to upload:</Div> <DivID= "Custom-queue" ></Div> <inputID= "Custom_file_upload"type= "File"name= "Filedata"class= "button"/> <inputtype= "button"ID= "Up"name= "Up"value= "Upload"class= "button"/> <inputtype= "button"ID= "Clear"name= "Clear"value= "Empty"class= "button"/> </Div> </Div></Body></HTML>
String space = "";//Multiple Picture time spacer
The ProcessRequest method code for the 5 Uploadhandler class is as follows:
Public voidProcessRequest (HttpContextContext) {intType= hrsiterequest.Getformint ("Type", 0);imguputilsUp= Newimguputils(); Context.Response.Write (UP.Uploadpic (context.Request.Files,"FileData", Commonut.Config.Getuploadimgconfig (type))); }The above imguputils is one of the pictures mentioned above, such as proportional compression processing class, Up.uploadpic (String arg1,string arg2) This method is to return the image stored in the picture path,
In general, the database is stored in the image path, when displayed in the Web page, through the image of the SRC splicing, you can get a website image URL. Then through the above Default.aspx page JS we can see, in fact, JS through the asynchronous upload returned after the URL, put it in the Picture text box, the last time the data submitted, the path is stored in the database, the specific is such a way of thinking. So take a look at the actual diagram of the page actually running.

6 post-operation effects such as:

7. When finished, fill in the text box:

When the entire form is last submitted, the URL of the image is stored in the database.

8 After selecting two files, click Upload, you can see the UploadFile folder will increase these two files.

The above simply implemented an upload function, relying on the function uploadify implementation, the parameters of the Uploadify function is in JSON format, you can modify the key value of the JSON object to customize the settings, If multi is set to TRUE or false to control whether multiple file uploads are possible, the following key values are described below:

The relative path to the uploader:uploadify.swf file, which is a button with a text browse, and then fades out of the Open File dialog box, the default value: uploadify.swf.
Script: The relative path of the spooler. Default value: uploadify.php
Checkscript: The relative path of the spooler that is used to determine whether the uploaded file is present on the server
Filedataname: Sets a name for the server handler to fetch data from the uploaded file according to that name. Default is Filedata
Method: Submit by post or get default to post
Scriptaccess:flash the access mode of the script file, if the local test is set to always, the default value: Samedomain
Folder: The directory where files are uploaded.
Queueid: The ID of the file queue that matches the ID of the div holding the file queue.
Queuesizelimit: When multiple file generation is allowed, set the number of selected files, the default value: 999.
Multi: When set to true, multiple files can be uploaded.
Auto: Set to True when the file is selected and uploaded directly, false need to click the Upload button before uploading.
Filedesc: This property value must be set after the Fileext property is valid to set the prompt text in the Select File dialog box, such as setting Filedesc as "Please select RAR doc PDF file
Fileext: Sets the type of file that can be selected, in the form of ' *.doc;*.pdf;*.rar '.
SizeLimit: Size limit for uploaded files.
Simuploadlimit: The default number of simultaneous uploads is allowed: 1.
ButtonText: The text of the browse button, default: Browse.
BUTTONIMG: The path to the picture of the browse button.
Hidebutton: Set to True to hide the picture of the browse button.
Rollover: The value is true and False when set to True when the mouse moves over the browse button with a reversal effect.
Width: Set the browse button to the default value: 110.
Height: Sets the altitude of the browse button, the default value: 30.
Wmode: Setting this to transparent can make the flash background file of the browse button transparent, and the Flash file will be placed at the highest level of the page. Default value: Opaque.
CANCELIMG: Select the Close button icon on each file after the file is selected in the file queue,
The value of the key described above is either a string or a Boolean type, which is simpler, and the value of the key to be introduced is a function that returns some information to the user when selecting a file, an error, or some other action.
OnInit: Do some initialization work.
OnSelect: triggered when selecting a file, the function has three parameters
Event: Events object.
Queueid: A unique identifier for the file, consisting of 6 random characters.
Fileobj: The selected file object has a name, size, CreationDate, Modificationdate, type 5 properties.onselectonce: Triggered when a file is selected in a single file or multiple file upload. The function has two parameters Event,data,data object has the following properties:

    • FileCount: Select the total number of files.
    • filesselected: Select the number of files at the same time, if you select 3 files at a time, the property value is 3.
    • Filesreplaced: If A and b two files already exist in the file queue, select a and B when selecting the file again, and the property value is 2.
    • Allbytestotal: The total size of all selected files.

OnCancel: triggered when you click the Close button of a file in the file queue or click Cancel upload. The function has event, Queueid, Fileobj, data four parameters, the first three parameters and OnSelect in three parameters, the data object has two properties FileCount and Allbytestotal.

    • FileCount: The number of files remaining in the file queue after a file is canceled.
    • Allbytestotal: The size of the remaining files in the file queue after canceling a file.

Onclearqueue : triggered when the function fileuploadclearqueue is called. There are two parameters for event and data, and two corresponding parameters in onCancel .

onqueuefull: triggered when Queuesizelimit is set and the number of files selected exceeds the value of Queuesizelimit. The function has two parameters of event and Queuesizelimit.

OnError: triggered when an error occurs during upload. The function has the event, Queueid, Fileobj, errorobj four parameters, of which the first three parameters, Errorobj object has type and info two properties.

    • Type: Error types, there are three kinds of ' HTTP ', ' IO ', or ' Security '
    • Info: Description of the error

OnOpen: triggered when the upload is clicked, if Auto is set to true, it is triggered when the file is selected, and if more than one file is uploaded, the entire file queue is traversed. The function has the event, Queueid, fileobj three parameters, the parameter is interpreted as above.

onprogress : Triggered when the upload is clicked, if Auto is set to true, it is triggered when the file is selected, and if more than one file is uploaded, it traverses the entire file queue and fires after OnOpen. This function has event, Queueid, Fileobj, data four parameters, the first three parameters are explained above. The data object has four properties percentage, bytesloaded, allbytesloaded, Speed:

    • Percentage: Percentage of current completion
    • Bytesloaded: The size of the current upload
    • Allbytesloaded: The size of the file queue that has already been uploaded
    • Speed: Upload Rate kb/s

oncomplete: Triggers when file upload is complete. The function has four parameters event, Queueid, Fileobj, response, data five parameters, the first three parameters ibid. Response is the value returned by the spooler, in the example above, 1 or 0,data has two properties FileCount and speed

    • FileCount: The number of files remaining without uploading completed.
    • Speed: Average rate of file uploads kb/s

Note: The Fileobj object is somewhat different from the one mentioned above, and the OnComplete Fileobj object has a filepath attribute to remove the path to the uploaded file.

onallcomplete: triggers when all files in the file queue are uploaded. The function has an event and data two parameters, and data has four properties, respectively:

    • Filesuploaded: The number of uploaded files.
    • Errors: The number of errors occurred.
    • Allbytesloaded: The total size of all uploaded files.
    • Speed: Average upload rate kb/s

Introduction to related functions

In the above example, Uploadifyupload and uploadifyclearqueue two functions have been used, in addition to several functions:

uploadifysettings: You can dynamically modify the key values described above, such as the following code

$ (' #uploadify '). Uploadifysettings (' folder ', ' JS ');

If the Upload button event is written as follows, the file will be uploaded to the directory defined in the Uploadifysettings

<a href= "javascript:$ (' #uploadify '). Uploadifysettings (' folder ', ' JS ');
$ (' #uploadify '). Uploadifyupload () "> Upload </a>

uploadifycancel: The function accepts a queueid as a parameter that cancels the file specified Queueid in the file queue.

$ (' #uploadify '). Uploadifycancel (ID);
Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.