Java servlet-based file asynchronous upload _java

Source: Internet
Author: User
Tags domain list

Here using a servlet-based file asynchronous upload, good nonsense not much to say, directly on the code ...

Package com.future.zfs.util;
Import Java.io.File;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import Java.util.Iterator;

Import java.util.List;
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.FileUploadException;
Import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
Import Org.apache.commons.fileupload.disk.DiskFileItemFactory;

Import Org.apache.commons.fileupload.servlet.ServletFileUpload; @SuppressWarnings ("Serial") public class Fileuploadservlet extends HttpServlet {final long max_size = 10 * 1024 * 1024 //Set Upload file maximum 10M//Allow uploaded file format list final string[] Allowtype = new string[] {"JPG", "JPEG", "gif", "TXT", "Doc", "Docx", "MP3"

  , "WMA", "M4A", "xls"};
  Public Fileuploadservlet () {super (); public void Destroy () {SUPER.DESTROy (); @Override protected void Service (HttpServletRequest request, httpservletresponse response) throws Servletexce
    Ption, IOException {response.setcontenttype ("text/html");

    Set character encoding to UTF-8, which supports Chinese character display response.setcharacterencoding ("UTF-8");
    Instantiate a hard disk file factory to configure the upload component Servletfileupload diskfileitemfactory dfif = new Diskfileitemfactory (); Dfif.setsizethreshold (4096)//Set the amount of memory used to temporarily store files when uploading files, this is 4K. More than one part will temporarily have the hard drive dfif.setrepository new file ( Request.getrealpath ("/") + "Uploadtemp"))/set the directory where temporary files are stored, the Uploadtemp directory under the Web root directory//The upload component is instantiated with the above factory Servletfileu
    Pload SFU = new Servletfileupload (DFIF);

    Set Maximum upload size Sfu.setsizemax (max_size);
    PrintWriter out = Response.getwriter ();
    From request to get all the uploaded domain list filelist = null;
    try {filelist = sfu.parserequest (request); The catch (Fileuploadexception e) {//processing file size is too large an exception if (e instanceof sizelimitexceededexception) {out.println ("{ Message: ' File size exceeds the specified size: ' +max_size+ ' wordSection '} ');
      Return
    } e.printstacktrace ();
      //No file upload if (filelist = null | | filelist.size () = 0) {out.println ("{message: ' Select Upload file '}");
    Return
    //Get all uploaded files iterator Fileitr = Filelist.iterator ();
      Loops All Files while (Fileitr.hasnext ()) {Fileitem fileitem = null;
      String path = null;
      Long size = 0;
      Get current File Fileitem = (Fileitem) fileitr.next (); Ignore the simple form field instead of the File field (<input type= "text"/>) of the upload domain if (fileitem = = NULL | | Fileitem.isformfield ()) {cont
      Inue;
      //Get the full path of the file: Path = Fileitem.getname ();
      Get the size of the file = Fileitem.getsize (); if ("". Equals (path) | |
        Size = = 0) {out.println ("{message: ' Please select Upload file '}");
      Return
      ///Gets the filename of the removal path String t_name = path.substring (Path.lastindexof ("\") + 1);
      Gets the file's extension (will get full name without extension) String T_ext = t_name.substring (T_name.lastindexof (".") + 1); Refusal to accept the prescribed file formatThe file type int allowflag = 0;
      int allowedextcount = Allowtype.length;
      for (; Allowflag < Allowedextcount, allowflag++) {if (Allowtype[allowflag].equals (T_ext)) break;
        } if (Allowflag = = allowedextcount) {String message = ' ";
                        for (Allowflag = 0; Allowflag < Allowedextcount; allowflag++) {message+= "*." + Allowtype[allowflag]
        + " ";
        } out.println ("{message: ' Please upload the following type of file" +message+ "}");
      Return
      Long now = System.currenttimemillis ();
      Build the file name saved after uploading based on system time String prefix = string.valueof (now); The complete path to the saved final file, saved in the upload directory under the Web root directory String u_name = Request.getrealpath ("/") + "upload/" + prefix + "." +
      T_ext;
      The original filename path=request.getrealpath ("/") + "upload/" +path;
        try {//Save files Fileitem.write (new file (path));
        Response.setstatus (200); Out.println ("{message:\" file uploaded successfully.) Saved as: "+ prefIX + "." + t_ext + "File size:" + size + "byte \"} ";
      catch (Exception e) {e.printstacktrace ();
 }

    }
  }
}

Xml

<servlet>
    <servlet-name>fileUploadServlet</servlet-name>
    <servlet-class> com.future.zfs.util.fileuploadservlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>fileUploadServlet</servlet-name>
    <url-pattern>/fileuploadservlet</ Url-pattern>
  </servlet-mapping>

Upload page

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >  

Note that you need to set the Response.setcontenttype ("text/html") when using ajaxfileupload based on the servlet upload; datatype: ' JSON ' is set to JSON still set Response.setcontenttype (' text/html '), otherwise the data returned by the server side is not obtained and a dialog box pops up.

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.