Using Ajaxfileupload.js to implement upload file function _jquery

Source: Internet
Author: User

Always upload files are using form form to upload files, but also saw someone using JS upload file, but it seems quite simple also did not how to ignore. This is a sudden day to upload files in this way, and there are some problems during the period. So record it and make it easier to see the problems later.

The first is the introduction of JS and ajaxfileupload files, this does not need to say more.

Then there is the AJAX request background address. The code is as follows:

 <div class= "Btn-file-box pos-rel" >
   <input type= "file" id= "upload" name= "upload" style= "Font-size:0;o" pacity:0;width:100%;height:100%;p osition:absolute;left:0;top:0; " />
 <span class= "btn" > select File </span>
 </div> 


$ ("#upload"). On (' Change ', function () {
    $.ajaxfileupload {
      URL: '/test/user/imgupload ',//Background request address
      type: ' Post ',//Request mode when you want to submit a custom parameter, this parameter is set to post
      secureuri:false,//Whether security commits are enabled and false by default. 
      fileelementid: ' Upload ',//the ID of the file field that needs to be uploaded, that is, <input type= "file" >.
      dataType: ' json ',//The data type returned by the server. can be for xml,script,json,html. If you do not fill in, jquery will automatically judge. If the JSON returns with the pre, this can be resolved by modifying it to JSON.
      success:function (JSON, status) {/////////////////////////////////
         alert (json.retmsg);
      },
      error:function (JSON, status, E) {//Commit failed automatic execution of the handler function.
        
      }
    });
  }); 

The foreground code is complete and the background code is developed.

Package Com.roc.test;import Java.io.file;import java.util.List;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import Javax.ws.rs.Consumes;
Import Javax.ws.rs.POST;
Import Javax.ws.rs.Path;
Import javax.ws.rs.Produces;
Import Javax.ws.rs.QueryParam;
Import Javax.ws.rs.core.Context;
Import Javax.ws.rs.core.MediaType;
Import Net.sf.json.JSONObject;
Import Org.apache.commons.fileupload.FileItem;
Import Org.apache.commons.fileupload.disk.DiskFileItemFactory;
Import Org.apache.commons.fileupload.servlet.ServletFileUpload;
Import Org.jboss.resteasy.annotations.providers.jaxb.json.BadgerFish; Import org.springframework.stereotype.controller;import net.sf.json.jsonobject;/** * Upload file * @author LIAOWP * * * * * * @Contr Oller @Path ("/user") public class Uploadimg {@Path ("/imgupload") @POST @Produces ("Application/json; Charset=utf-8 ") @Consumes (mediatype.multipart_form_data) @BadgerFish public jsonobject upload (@QueryParam (" OrderId ") String orderId, @Context httpservletrequest request, @Context httpservletresponse response) {Jsonobject jsonobj = new JSON
    Object (); String file_path=request.getsession (). Getservletcontext (). Getrealpath ("/") +file.separator+ "Corpfile" +
    file.separator;//File Store path String upload_file_path= "";  
    File file =new file (File_path);
       if (!file.exists () &&!file.isdirectory ()) {//If the folder does not exist then create FILE.MKDIR ();
    Upload_file_path=file_path;
    }else{Upload_file_path=file_path; } diskfileitemfactory factory = new Diskfileitemfactory (); Set the factory factory.setrepository (new file (File_path))//Set file storage location Factory.setsizethreshold (2048 * 1024);//Set size if file
    Smaller than the set size, put in memory, if greater than the words then put into the disk servletfileupload upload = new Servletfileupload (factory);
    Upload.setheaderencoding ("Utf-8");/here is the code for the Chinese file name processing, in fact, only one line String filename = "";
    List<fileitem> list;
    Jsonobject jsonobj = new Jsonobject (); try {list = Upload.parserequest (requesT);
          for (Fileitem item:list) {if (Item.isformfield ()) {String name = Item.getfieldname ();
        String value = item.getstring ("Utf-8");
          else {String name = Item.getfieldname ();
          String value = Item.getname ();
          FileName =name + ". jpg";
            if (Item.getsize () > 10485760) {//Hello, upload file is less than 10m!
            Jsonobj.put ("RetCode", "100"); Jsonobj.put ("retmsg", "Hello, upload file to less than 10m!
            "):} else {//Upload success Item.write (new File (Upload_file_path, fileName));
            System.out.println (File.separator + "Corpfile" + File.separator + fileName);
            Jsonobj.put ("RetCode", "0"); Jsonobj.put ("retmsg", "Hello, upload success!")
          ");
      catch (Exception e) {//upload failed e.printstacktrace ();       Jsonobj.put ("RetCode", "9999");
    Jsonobj.put ("retmsg", "Hello, file upload failed,");
  return jsonobj;
 }

}

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.