A simple jQuery plug in ajaxfileupload.js implementation of ajax upload file example

  • 2020-03-30 03:25:51
  • OfStack

JQuery plug-in AjaxFileUpload can achieve ajax file upload, the plug-in is very simple to use, first to learn the correct use of the AjaxFileUpload plug-in, and then to learn some common error messages and solutions.

Directions for use

JQuery library files and AjaxFileUpload library files are required

Using the instance

One, include the file part


<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="ajaxfileupload.js"></script>

Second, the HTML part


<img id="loading " src="loading.gif" style="display:none;">
<input id="fileToUpload " type="file" size="20" name="fileToUpload " class="input">
<button class="button" id="buttonUpload" onclick="return ajaxFileUpload ();"> upload </button>

Only three elements are required, a small dynamically loaded icon, a file field, and a button
Note: no form is required to upload files using the AjaxFileUpload plugin, as follows:

< 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 file domain ID and name, the ajaxFileUpload plug-in fileElementId parameter needs to get the file domain ID, if you handle the upload file operation, you need to know the file domain name, in order to get the upload file information, the relationship between the two must be clear.

Third, the javascript part


<script type="text/javascript"> 
function ajaxFileUpload (){ 
loading();//Load small ICONS dynamically
$.ajaxFileUpload ({ 
url :'upload.php', 
secureuri :false, 
fileElementId :'fileToUpload', 
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 represents the file path to handle the file upload operation, and you can test whether the url can be directly accessed in the browser, as shown in: upload.php
2, fileElementId represents the file field ID, as above: fileToUpload
3. Whether secureuri enables secure commit, false by default
4. DataType data, json or javascript
5. Success submits the successful post-processing function
6. Error submission failure handling function

There are two methods above, a small dynamic loading icon prompt function loading() and ajaxFileUpload file upload $.

At the same time we need to be aware of the relevant error tips

1. SyntaxError: missing; Before the statement error
If this error occurs, you need to check whether the url path is accessible

2, SyntaxError: syntax error
If this error occurs, you need to check for syntax errors in the PHP file that handles the submit operation

3, SyntaxError: invalid property id error
If this error occurs, you need to check whether the attribute ID exists

4. SyntaxError: missing} in XML expression error
If this error occurs, you need to check that the file name is consistent or does not exist

5. Other custom errors
You can use the variable $error direct printing method to check whether the parameters are correct, compared with the above invalid error prompt or more convenient.

Using jQuery plugin AjaxFileUpload to upload files without refreshing is very useful. Due to its simplicity and ease of use, this plugin has the largest number of users compared with other file uploads 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 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:'gggn',");
  //Response.Write("error:'aan'");
  //Response.Write("}");
  Response.End();
 }
}

Other comments:

Page code:


<html>
    <!-- Introduce correlation js File, relative path   -->
    <script type="text/javascript" src="js/jquery.js"></script>
      <script type="text/javascript" src="js/ajaxfileupload.js"></script>     <!-- Function that performs the action of uploading a file -->
      <script type="text/javascript">
          function ajaxFileUpload(){
               $.ajaxFileUpload(
                   {
                url:'update.do?method=uploader',            //Need to link to server address
                secureuri:false,
                fileElementId:'houseMaps',                        //File selection box id attribute
                dataType: 'xml',                                     //The format returned by the server can be json
                success: function (data, status)            //This is equivalent to the use of a try block in Java
                {     
                    $('#result').html(' Add a success ');
                },
                error: function (data, status, e)            //The equivalent of a Java catch block is
                {
                    $('#result').html(' Add failure ');
                }
            }
                  
               );
             
          }
      </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:


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());            //Specifies the path to the file store and the 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;
    }
}


Related articles: