An example of a simple jQuery plug-in ajaxfileupload. js to implement ajax File Upload

Source: Internet
Author: User

The jQuery plug-in AjaxFileUpload can upload ajax files. This plug-in is very simple to use. First, let's take a look at the correct method for using the AjaxFileUpload plug-in, and then learn some common error information and solutions.

Instructions for use

You need to use the jQuery library file and the AjaxFileUpload Library File

Use instance

1. Contains the file section

Copy codeThe Code is as follows:
<Script type = "text/javascript" src = "jquery. js"> </script>
<Script type = "text/javascript" src = "ajaxfileupload. js"> </script>

Ii. HTML Section

Copy codeThe Code is as follows:

<Input id = "fileToUpload" type = "file" size = "20" name = "fileToUpload" class = "input">
<Button class = "button" id = "buttonUpload" onclick = "return ajaxFileUpload ();"> upload </button>

You only need three elements, one dynamic loading small icon, one file domain, and one button.
Note: you do not need to use the AjaxFileUpload plug-in to upload a file:

<Form name = "form" action = "" method = "POST" enctype = "multipart/form-data">
...... Related html code ......
</Form>
Because the AjaxFileUpload plug-in automatically generates a form submission form.

For the file domain ID and name, The fileElementId parameter of the ajaxFileUpload plug-in needs to obtain the file domain ID. If you want to process the file upload operation, you need to know the file domain name to obtain the information of the file to be uploaded, the relationship between the two must be clear.

Iii. javascript

<Script type = "text/javascript"> function ajaxFileUpload () {loading (); // dynamically load small icons $. ajaxFileUpload ({url: 'upload. php ', secureuri: false, fileElementId: 'filetupload', dataType: 'json', success: function (data, status) {if (typeof (data. error )! = 'Undefined') {if (data. error! = '') {Alert (data. error);} else {alert (data. msg) ;}}, error: function (data, status, e) {alert (e) ;}}) return false;} function loading () {$ ("# loading "). ajaxStart (function () {$ (this ). show ();}). ajaxComplete (function () {$ (this ). hide () ;}) ;}</script>

Description of main parameters:
1. the url indicates the file path for processing the file upload operation. You can test whether the URL can be accessed directly in the browser. For example, upload. php
2. fileElementId indicates the file domain ID, as shown above: fileToUpload
3. Whether secureuri enables secure submission. The default value is false.
4. dataType data. Generally, the original structure of json and javascript is selected.
5. success: the post-processing function is successfully submitted.
6. error submission failure Handler

There are two methods on the top, one dynamic loading small icon prompts the loading () function and ajaxFileUpload File Upload $. the ajaxFileUpload () function, which is used with jQuery. ajax () functions are similar and easy to use. Here I omit PHP to process uploaded files. Using the jQuery plug-in AjaxFileUpload to implement ajax files is that simple.

At the same time, we need to know the relevant error messages

1. SyntaxError: missing; before statement Error
If this error occurs, check whether the url path can be accessed.

2. SyntaxError: syntax error
If this error occurs, check whether the PHP file for processing the submitted operation has a syntax error.

3, SyntaxError: invalid property id Error
If this error occurs, check whether the property ID exists.

4, SyntaxError: missing} in XML expression Error
If this error occurs, check whether the file domain name is consistent or does not exist.

5. other custom errors
You can directly print the variable $ error to check whether the parameters are correct, which is much more convenient than the above error prompts.

It is very practical to use the jQuery plug-in AjaxFileUpload to implement the resumable upload of files. Because of its ease of use, this plug-in has the largest number of users compared with other file upload plug-ins and is highly recommended.
 
Processing page:

Using System; using System. collections; using System. configuration; using System. data; using System. web; using System. web. security; using System. web. UI; using System. web. UI. htmlControls; using System. web. UI. webControls; using System. web. UI. webControls. webParts; public partial class web_ajax_FileUpload: System. web. UI. page {protected void Page_Load (object sender, EventArgs e) {HttpFileCollection files = HttpContext. current. request. files; // if (files [0]. contentLength> 5) // {// Response. write ("{"); // Response. write ("msg: '" + files [0]. fileName + "',"); // Response. write ("error: 'file upload failed'"); // Response. write ("}"); // else // {// Response. write ("{"); // Response. write ("msg: 'No file was uploaded ',"); // Response. write ("error: 'file upload failed'"); // Response. write ("}"); //} files [0]. saveAs ("d:/adw.jpg"); Response. write ("{"); Response. write ("msg: 'A',"); Response. write ("error:'' "); Response. write ("}"); // Response. write ("{"); // Response. write ("msg: 'ggg \ n',"); // Response. write ("error: 'aa \ N'"); // Response. write ("}"); Response. end ();}}

Supplemented by other netizens:

Page code:

Copy codeThe Code is as follows:
<Html>
<! -- Introduce relevant js files and relative paths -->
<Script type = "text/javascript" src = "js/jquery. js"> </script>
<Script type = "text/javascript" src = "js/ajaxfileupload. js"> </script>

<! -- Execute the function for uploading files -->
<Script type = "text/javascript">
Function ajaxFileUpload (){
$. AjaxFileUpload (
{
Url: 'Update. do? Method = uploader ', // link to the server address
Secureuri: false,
FileElementId: 'housemaps ', // id attribute of the file selection box
DataType: 'xml', // format returned by the server, which can be json
Success: function (data, status) // equivalent to the usage of the try statement block in java
{
Certificate ('{result'{.html ('added successfully ');
},
Error: function (data, status, e) // equivalent to the catch Block usage in java
{
Certificate ('{result'{.html ('add failed ');
}
}

);

}
</Script>
</Head>
<Body>
<Form method = "post" action = "update. do? Method = uploader "enctype =" multipart/form-data ">
<Input type = "file" id = "houseMaps" name = "houseMaps"/>
<Input type = "button" value = "Submit" onclick = "ajaxFileUpload ()"/>
</Form>
<Div id = "result"> </div>

</Body>
</Html>

Server code:

Copy codeThe Code is as follows:
Public class UpdateAction extends DispatchAction {

Public ActionForward uploader (ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response ){
UpFormForm upFormForm = (UpFormForm) form;
FormFile ff = upFormForm. getHouseMaps ();
Try {
InputStream is = ff. getInputStream ();
File file = new File ("D:/" + ff. getFileName (); // specify the File storage path and file name
OutputStream OS = new FileOutputStream (file );

Byte [] B = new byte [1024];
Int len = 0;
While (len = is. read (B ))! =-1 ){
OS. write (B, 0, len );
}
OS. close ();
Is. close ();
} Catch (Exception e ){
E. printStackTrace ();

}

Return null;
}
}

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.