Jquery uploadify and apache Fileupload implement asynchronous Fileupload examples

  • 2020-04-01 03:18:27
  • OfStack

JQuery Uploadify + Apache Fileupload asynchronous Fileupload example
1. You can limit the size and type of uploaded files. Theoretically, any type of file can be uploaded (you can configure it according to the API);
2. The background USES Apache commons-fileupload-1.3.1.jar as the uploading toolkit, and this example supports one-time multi-file uploading;
3, the file upload directory can be arbitrarily specified, please configure in web.xml;
Uploadify API can be found in the http://www.uploadify.com/documentation/

FileUploadServlet


package com.xiaoxing.upload;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
 * <h1>Apache Fileupload File upload ( 2014-5-3 ) </h1>
 * <p>1 If you are interested in this example and would like to learn more, please join us Java Private school online learning community ( 329232140 ) </p>
 * <p>2 , small changes to this example can be transplanted to your actual project. </p>
 */
public class FileUploadServlet extends HttpServlet {

    private static final long serialVersionUID = 7579265950932321867L;

    //Set the file upload directory by default (if you did not configure it in web.xml)
    private String uploadDir = "c:/"; //File upload directory
    private String tempUploadDir = "c:/"; //File temporary storage directory (session destroyed by the listener automatically deleted)

    
    @Override
    public void init() throws ServletException {
        //Get the real hard disk directory where the project is located
        String path = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
        path = path.substring(0, path.indexOf("WEB-INF"));
        //To judge the existence of a target, establish if it does not exist
        String uploadDir = path.concat(this.getInitParameter("uploadDir"));
        String tempUploadDir = path.concat(this.getInitParameter("tempUploadDir"));
        File f_uploadDir = new File(uploadDir);
        File f_tempUploadDir = new File(tempUploadDir);
        if (!f_uploadDir.exists()) {
            f_uploadDir.mkdirs();
        }
        if (!f_tempUploadDir.exists()) {
            f_tempUploadDir.mkdirs();
        }
        //Assign a value to a variable
        this.uploadDir = uploadDir;
        this.tempUploadDir = tempUploadDir;
    }

    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.setResponse(response);
        PrintWriter out = response.getWriter();
        out.print("{"error":"-1""); //Illegal submission method
    }

    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.setResponse(response); //Set the response type for front-end parsing
        PrintWriter out = response.getWriter();
        String result = "";
        try {
            //Check if this is a file upload request
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (isMultipart) {
                DiskFileItemFactory factory = new DiskFileItemFactory(); //Create a factory disk-based file entry
                factory.setRepository(new File(tempUploadDir)); //Configure the repository (when securing a temporary location)
                ServletFileUpload upload = new ServletFileUpload(factory); //Create a new file upload handler
                upload.setSizeMax(1024 * 1024 * 100); //Set the size limit of overall requirements (it is recommended to set the front and background separately, because different plug-ins are used in the front and background)
                List<FileItem> items = upload.parseRequest(request); //Parse the request
                Iterator<FileItem> iter = items.iterator(); //Handle uploaded items
                while (iter.hasNext()) { //If you upload multiple files at once, you will save them separately
                    FileItem item = iter.next();
                    if (!item.isFormField()) { //Filter the non-file type fields in the form
                        if (!"".equals(item.getName())) { //Filters input for non-file types
                            String s_name = item.getName(); //Get the original file name
                            int position = s_name.lastIndexOf(".");
                            String s_fileType = s_name.substring(position, s_name.length()); //Get file suffix
                            String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
                            String s = uploadDir.concat("/").concat(date).concat("/");
                            //Here, the files are saved in directories by date
                            File sf = new File(s);
                            if (!sf.exists()) {
                                sf.mkdirs();
                            }
                            String s_filePath = s.concat(UUID.randomUUID().toString()).concat(s_fileType);
                            File path = new File(s_filePath);
                            item.write(path);
                            result += s_filePath.concat(",");
                        } else {
                            result = "";
                            break;
                        }
                    }
                }
            } else {
                result = "";
            }
            String s_resultJSON = this.jointJSON(result); //Concatenation returns the front-end JSON
            out.print(s_resultJSON);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.flush();
            out.close();
        }
    }

    
    private String jointJSON (String result) throws UnsupportedEncodingException {
        String str = "";
        if(!"".equals(result)) {
            String rs[] = result.split(",");
            StringBuffer buffer = new StringBuffer("{"rows":[");
            for (int i = 0; i < rs.length; i++) {
                String s_tmpName = rs[i];
                s_tmpName = s_tmpName.substring(uploadDir.length(), s_tmpName.length());
                buffer.append("{"name":"").append(s_tmpName).append(""},");
            }
            str = buffer.toString();
            str = str.substring(0, str.length() - 1).concat("]}");
        } else {
            str = "{"error":"-2""; //Upload failed
        }
        return str;
    }

    /**
     *  Set the response type ContentType for "application/x-json"
     * @param response
     */
    private void setResponse(HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("cache-control", "no-cache");
    }
}

Test_upload. HTML


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery Uploadify + Apache Fileupload Sample asynchronous file upload (2014-5-3)</title>
<link rel="stylesheet" type="text/css" href="/js/uploadify/uploadify.css">
<script src="/js/jquery-1.9.0.js"></script>
<script src="/js/uploadify/jquery.uploadify.min.js"></script>
<script type="text/javascript">
$(function() {
 $('#fileupload').uploadify({
     'method'   : 'post',
     'buttonText' : 'flash Upload a file ',
     'fileSizeLimit' : '1024KB',
     'fileTypeExts' : '*.gif; *.jpg; *.png',
  'swf'      : '/js/uploadify/uploadify.swf',
  'uploader' : '/upload', //This is the path to upload the image, which is the servlet I configured in web.xml
  'onUploadSuccess' : function(file, data, response) { //The data returned after the picture upload is processed here
      var ary = eval("(" + data + ")").rows;
      for(var i = 0; i < ary.length; i++) {
          $("#J_div").append("<img alt=' The picture ' src='/upload/images" + ary[i].name + "' width='200px' height='200px'>");
      }
     }
 });
});
</script>
</head>
<body>
 <h2>jQuery Uploadify + Apache Fileupload Sample asynchronous file upload (2014-5-3)</h2>
 <p>1 Can be limited to upload file size and type, theoretically any type of file can be uploaded (according to their own api Configuration can); </p>
 <p>2 , background use Apache commons-fileupload-1.3.1.jar As an upload toolkit, this example supports multiple file uploads at once; </p>
 <p>3 File upload directory can be arbitrarily specified, please in web.xml The configuration; </p>
 <p>4 , for the already uploaded pictures did not query to this page, this part is left to you to do. </p>
 <p>Uploadify api  As shown in the http://www.uploadify.com/documentation/</p>
 <p style="color: red">* If you are interested in this example and would like to learn more, please join us Java Private school online learning community ( 329232140 ). </p>
 <input id="fileupload" type="file" name="img" multiple="multiple"/>
 <div id="J_div"></div>
</body>
</html>

web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" metadata-complete="true" version="3.0">
  <welcome-file-list>
   <welcome-file>test_upload.html</welcome-file>
  </welcome-file-list>

  <servlet>
    <description> Dedicated to handling upload operations servlet</description>
        <servlet-name>FileUploadServlet</servlet-name>
        <servlet-class>com.xiaoxing.upload.FileUploadServlet</servlet-class>
        <init-param>
         <description> The official directory where the files are stored, you can configure it yourself </description>
         <param-name>uploadDir</param-name>
         <param-value>/upload/images/</param-value>
        </init-param>
        <init-param>
         <description> File storage temporary directory, you can configure their own, the file is automatically deleted by the following configuration of the listener. </description>
         <param-name>tempUploadDir</param-name>
         <param-value>/upload/temp</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>FileUploadServlet</servlet-name>
        <url-pattern>/upload</url-pattern>
    </servlet-mapping>

    <listener>
     <description> Temporary file resources clean, kit comes with us, do not need to write </description>
     <listener-class>org.apache.commons.fileupload.servlet.FileCleanerCleanup</listener-class>
   </listener>

</web-app>


Related articles: