JQuery ajaxupload Chinese Usage API and Demo sample

Source: Internet
Author: User

1, ajaxupload upload plugin

The browser forces us to upload using the file input control (<input type= "file"/>), but the style of this control cannot be modified. In addition, form-based uploads appear obsolete in the face of popular AJAX applications. We can use Flash to solve this problem, but JavaScript can actually do a great job.

The Ajax upload file upload plugin allows you to upload multiple plugins without refreshing the page, using any element to display the file Selection window. It works in all major browsers, starting with version 2.0 and not requiring any libraries to run. The Ajax upload file upload plugin does not pollute any namespaces, so it is compatible with jquery,prototypejs,mootools other JavaScript libraries.

Demo instance
Here is an example of using the Ajaxupload plugin under jquery.

Download
Version 3.6 released on 2009-03-10

Issues, contributions and latest versions
The project has recently moved to GitHub and you are welcome to toss it. You are also more likely to use issue tracking (issue tracker) to leave comments, bug reports and requirements. You have to register on GitHub first.

2, how to use it?

Create an upload
First, you need to create a button. (any element can be used)

-Shrinkage HTMLCode Run code[If the run is ineffective, save the source code as an HTML file]<div id= "upload_button" > Upload </div>

Next, you should create an Ajax upload instance. You can use the following code to create the simplest form:

-Shrinkage JavaScriptCode//You must create it after the DOM is ready.
Use $ (document) under jquery. Ready
Prototype under the Document.observe ("dom:loaded"
New Ajaxupload (' upload_button_id ', {action: ' upload.php '});

Configuring Ajax Uploads

-Shrinkage JavaScriptCodeNew Ajaxupload (' #upload_button_id ', {
Server-side Upload script
Note: Files are not allowed to be uploaded to another domain
Action' Upload.php ',
The name of the file upload
Name' UserFile ',
Additional data sent
Data: {
Example_key1:' Example_value ',
Example_key2: ' example_value2′
},
Submit file after filtering
Autosubmit:True
The type of data that you want to return from the server
HTML (text) and XML auto-detection
It is useful when you use JSON as a response, in which case it is set to "JSON"
Also set the server-side response type to text/html, otherwise it will not work under IE6
Responsetype:False
//  file selection use
//  when Autosubmit is disabled it works
//  you can cancel the upload by returning false
// @ parameter file is the filename of the uploaded files
// @ parameter extension for that file (suffix name)
Onchange: function (file,  extension) {},
//  File upload
//  you can cancel the upload by setting back false 
// @ parameter file is the filename of the uploaded file
// @ parameter extension for that file (suffix name)
OnSubmit:  function (file, extension)  {},
//  called when the file upload is complete
span class= "NOTE" >//  Warning! Do not use the "false" string as the response of the server
// @ parameter file  refers to the uploaded file name
// @ parameter  response  refers to the server's response
Oncomplete: function (file, response)  {}
});

  Note: do not use data parameters to attach Dynamic Data, just like "Data: (Txt:textfield.value)" because it will allocate data when the Ajaxupload instance is created and will not change in the future. If you want to pass the text box to other data, use the SetData method in the onsubmit callback function.

Instance method
*submit– submitting files to the server (useful when autosubmit is disabled)
*disable– Disable the Upload button
*enable– Allow upload button
*destroy– Cleanup Ajaxupload objects
* SetData (data) – Overwrite parameters

-Shrinkage JavaScriptCodeYou can use these methods to configure the upload of Ajax
var upload = new Ajaxupload (' #div_id ', {action: ' upload.php '});
For example, when the user chooses something, set some parameters
Upload.setdata ({' example_key ': ' value '});
Or you can use these methods directly in the event function
New Ajaxupload (' div_id ', {
Action: ' upload.php ',
OnSubmit: function () {
Allow only one upload
This.disable ();
}
});
});

3. How do I access uploaded files?
For server-side code, the file appears to be uploaded in a simple form, so you can use any language you want.
You can access the upload file using:


* PHP: $_files[' UserFile ']
* Rails:params[:userfile]


note that ' userfile ' is the default value for the ' name ' option

You can access some other parameters by:


* PHP: $_post[' Yourkey ']
* Rails:params[:yourkey]

Server-side scripting
If you are using PHP, here is a simple example that I obtained directly from the PHP manual.

-Shrinkage PHPCode$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir. basename ($_files[' userfile ' [' name ']);
if (Move_uploaded_file ($_files[' userfile ' ['tmp_name '], $uploadfile)) {
echo "Success";
} Else {
Warning! Do not use the string "FALSE" as a response!
Otherwise the onsubmit event does not invoke the
echo "error";
}

ColdFusion file Upload. (Default quasi-system solution)

<cffunction name= "UploadFile" access= "remote" output= "false" >
<cfargument name= "UserFile" >
<cffile action= "Upload" filefield= "UserFile" destination= "directory/path/on/server/" >
<cfreturn "Whatever" >
</cffunction>

Here is an ASPX handler, please modify it to suit your needs:

-Shrinkage C#CodeUsing System;
Using System.Web;
Using System.IO;
PublicClass Filehandler:ihttphandler
{
public void processrequest (Httpcontext context)
{
string strfilename = path.getfilename (context. Request.files[0]. FileName);
string strextension = path.getextension (context. Request.files[0]. FileName). ToLower ();
string strsavelocation = context. Server.MapPath ( "Upload")  +  Context. Request.files[0]. SaveAs (strsavelocation);
Context. Response.contenttype =  "Text/plain";
Context. Response.Write ( "success");
}
public bool isreusable
{
get
{
span class= "kw" >return false;
}
}
}

4. How do I allow only certain file types?
The best way is to check the file type selected in the onsubmit callback function and let the function return False to cancel the upload of the selected invalid file. But don't forget to add a server-side security check.

-Shrinkage JavaScriptCodeNew Ajaxupload (' #button2, {
Action: ' upload.php',
Onsubmit:function (file, ext) {
if (! (ext &&/^ (jpg|png|jpeg|gif) $/.test (EXT))) {
Extension does not allow
Alert (' ERROR: Invalid file name extension! ‘);
Cancel Upload
return false;
}
}
});

5, how to work?
The plugin creates the Invisible file field control on the button you provide. So, when the user clicks on your button, the normal File Selection window will be displayed. After the user selects a file, the plug-in submits the form containing the file input box control into an IFRAME. Therefore, this is not a real Ajax upload, but it also brings the user experience.

6. License and Terms of use
Ajaxupload Upload plugin is completely free and subject to the MIT License license.

Second, I use PHP to make the simplest image upload using the demo

First, look at the diagram, briefly describe the operation.
1. Click the button to select the picture

2. Select a number of pictures, for example, I have selected three, selected and uploaded, the results are as follows

3. Results you can see the three images just uploaded under the uploads folder.

Please refer to the demo or source file for code.

You can simply click here: Chinese Demo page | Lite source File Download

Description
1, the source file download to the local, you need to modify the file processing PHP page code path. This path needs to be mapped to the folder you created to hold the picture or other file;
2, the source file and the online demo are different, the source file of the demo no logo, typesetting, advertising, such as pure demo, code concise, it should be helpful.
3, this example is able to upload images, you can remove the regular judgment, so that support other formats.
4, this example does not use the JavaScript library to assist, this is because the Ajax upload file upload plugin is purely javascript written, so do not rely on any JavaScript library, you can directly use JavaScript for multi-file upload.
5, online demo do not upload sensitive images, thank you for your cooperation.

Third, conclusion
This ajaxupload multi-file upload plugin is still very useful, this article will be the original project page content translated intact, time is hasty, translation or writing may be inaccurate, welcome message. The original project of the demo page is a bit messy, so I use javascript+php to achieve a very concise File Upload Demo page, I hope to help you.

Iv. Supplementary
Many people ask me, there is no way to support file type input. I thought about it today and changed it to achieve a similar <input type= "file"/> effect.
First, you need to call the modified JavaScript file, click here (right click to download): Modified version of JS.

First look at the effect, cut from IE6:

As a principle, use the combination of <input type= "text" id= "Uploadurl" > + <input type= "button" > to simulate the performance of <input type= "file"/>. Then, when the hidden file file field changes, let it be equal to the value of <input type= "text" >.

Specific effects you can click here: Effect Demo

As for the Code section, add a few lines of code similar to the following at the end of the JavaScript.

-Shrinkage JavaScriptCodevar ourl = document.getElementById ("Uploadurl"); //text box to display the local picture path
var ofile = document.getElementById ("Absfileinput");
if (ofile) {
Ofile.onchange = function () {
Ourl.value = This.value;
};
}

JQuery ajaxupload Chinese Usage API and Demo sample

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.