Java based servlet write upload download function similar to file server _java

Source: Internet
Author: User
Tags flush

I have nothing to do, wrote a servlet, to achieve the upload download function. After starting the service, you can be a small file server within a local area network.

First, preparatory work
download two jar packages:

Commons-fileupload-1.3.1.jar
Commons-io-2.2.jar

Second, create a Web project
My project name is: Z-upload

Third, the configuration 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 "
 id=" webapp_id "version=" 3.0 ">
 <display-name> z-upload</display-name>
 <servlet>
 <servlet-name>UploadService</servlet-name>
 <servlet-class>com.syz.servlet.UploadService</servlet-class>
 </servlet>
 < servlet-mapping>
 <servlet-name>UploadService</servlet-name>
 <url-pattern>/*< /url-pattern>
 </servlet-mapping>
</web-app>

As you can see from the above configuration, my servlet class is uploadservice, the matching URL is/*, which means matching all access URLs.

Iv. Writing servlet classes

 Package com.syz.servlet;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import Java.io.PrintWriter;
Import Java.text.SimpleDateFormat;
Import Java.util.Date;
Import Java.util.Iterator;

Import java.util.List;
Import Javax.servlet.ServletContext;
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.ProgressListener;
Import Org.apache.commons.fileupload.disk.DiskFileItemFactory;


Import Org.apache.commons.fileupload.servlet.ServletFileUpload;

  public class Uploadservice extends HttpServlet {public static final String LIST = "/list";

  public static final String FORM = "/form"; public static final StRing HANDLE = "/handle";

  public static final String DOWNLOAD = "/download";

  public static final String DELETE = "/delete";

  public static final String Upload_dir = "/upload";

  Private static final long serialversionuid = 2170797039752860765L; public void execute (httpservletrequest req, HttpServletResponse resp) throws Servletexception, IOException {Sys
    Tem.out.println ("Execute ...");
    SYSTEM.OUT.PRINTLN ("------------begin---------------");
    Req.setcharacterencoding ("UTF-8");
    String host = Req.getremotehost ();
    System.out.println ("Host:" + host);
    String uri = Req.getrequesturi ();
    System.out.println ("uri:" + uri);
    ServletContext ServletContext = This.getservletconfig (). Getservletcontext ();
    The basic path to the upload file String basepath = Servletcontext.getrealpath (Upload_dir);
    Context path String ContextPath = Servletcontext.getcontextpath ();
    System.out.println ("ContextPath:" + contextpath); Path String action after intercepting context = Uri.sUbstring (Contextpath.length ());
    System.out.println ("Action:" + action);
    Depending on the action different processing if (action.equals (form)) {form (ContextPath, RESP);
      else if (action.equals (HANDLE)) {Boolean ismultipart = Servletfileupload.ismultipartcontent (req);
      System.out.println ("Ismultipart:" + Ismultipart);
      if (!ismultipart) {return;
      } diskfileitemfactory factory = new Diskfileitemfactory ();
      File repository = (file) ServletContext. getattribute (Servletcontext.tempdir);
      System.out.println ("repository:" + Repository.getabsolutepath ());
      System.out.println ("BasePath:" + basepath);
      Factory.setsizethreshold (1024 * 100);
      Factory.setrepository (repository);
      Servletfileupload upload = new Servletfileupload (factory); Create listener Progresslistener Progresslistener = new Progresslistener () {public void update (long pbytesread, Lon G pcontentlength, int pitems) {SystEm.out.println ("Current File Size:" + pcontentlength + "\ t already processed:" + pbytesread);
      }
      };
      Upload.setprogresslistener (Progresslistener);
      list<fileitem> items = null;
        try {items = upload.parserequest (req);
        System.out.println ("Items Size:" + items.size ());
        iterator<fileitem> ite = Items.iterator ();
          while (Ite.hasnext ()) {Fileitem item = Ite.next (); if (Item.isformfield ()) {//Handle FormField}else{//handle file String fie
            Ldname = Item.getfieldname ();
            String fileName = Item.getname ();
            FileName = filename.substring (Filename.lastindexof (file.separator) + 1);
            String ContentType = Item.getcontenttype ();
            Boolean isinmemory = Item.isinmemory ();
            Long sizeinbytes = Item.getsize (); System.out.println (fieldName + "\ T" + FileName + "\ T" + ContentType + "\ T")+ isinmemory + "T" + sizeinbytes);
            File File = new file (BasePath + "/" + FileName + "_" + Getsuffix ());
            Item.write (file);
            InputStream in = Item.getinputstream ();
            OutputStream out = new FileOutputStream (file);
            Byte[] B = new byte[1024];
            int n = 0;
            while ((n = in.read (b))!=-1) {out.write (b, 0, N);
            } out.flush ();
            In.close ();
          Out.close ();
        Redirect to File list page String href1 = contextpath + list when finished processing;
      Resp.sendredirect (HREF1);
      catch (Fileuploadexception e) {e.printstacktrace ();
      catch (Exception e) {e.printstacktrace ();
    } else if (Action.equals (LIST)) {list (ContextPath, BasePath, resp);
      else if (action.equals (DOWNLOAD)) {String id = req.getparameter ("id"); SYSTEM.OUT.PRINTLN ("ID:" +ID);
      if (id = = null) {return;
      File File = new file (basepath);
      file[] list = File.listfiles ();
      int len = list.length;
      Boolean flag = false;
        for (int i = 0; i < len; i++) {File f = list[i];
        STRING fn = F.getname ();
          if (F.isfile () && Fn.lastindexof ("_") >-1) {String FID = fn.substring (Fn.lastindexof ("_"));
            if (Id.equals (FID)) {download (f, RESP);
            Flag = true;
          Break
      }} if (!flag) {NotFound (ContextPath, RESP);
      } else if (Action.equals (DELETE)) {String id = req.getparameter ("id");
      SYSTEM.OUT.PRINTLN ("ID:" + ID);
      if (id = = null) {return;
      File File = new file (basepath);
      file[] list = File.listfiles ();
      int len = list.length;
      Boolean flag = false;
        for (int i = 0; i < len; i++) {File f = list[i]; STRING fn= F.getname ();
          if (F.isfile () && Fn.lastindexof ("_") >-1) {String FID = fn.substring (Fn.lastindexof ("_"));
            if (Id.equals (FID)) {f.delete ();
            Flag = true;
          Break
        }} if (flag) {//After processing is redirected to the file list page String href1 = contextpath + list;
      Resp.sendredirect (HREF1);
      else {NotFound (contextpath, RESP);
    } else {show404 (contextpath, RESP);
  } System.out.println ("------------end---------------"); } private void show404 (String contextpath, HttpServletResponse resp) throws IOException {Resp.setcontenttype
    ("Text/html;charset=utf-8");
    PrintWriter out = Resp.getwriter ();
    String href1 = ContextPath + LIST;
    Out.write (" 

In fact, the Uploadservice class can directly implement the service method, and do not implement Doget, Dopost methods.

The above servlet I do not want to explain anything more, I see the code.

V. Effect drawing

1. Project Structure Chart


2.404 page

/* matches all including null characters, so the path in the picture matches and appears in else in the if judgment in Uploadservice because the action at this time is a null character.

3. File List page

4. Upload Form page

5. Download

6. Delete

7. File not found, if you point to delete, the file on the server already does not exist, then will enter this page

8. Packaged source Engineering and war packs

Where Z-upload is the Eclipse source project, Z-upload.war is the war package.

The whole project is two jar packs, a web.xml and a servlet class that can be copied from the past test, if lazy, can download

http://download.csdn.net/detail/yunsyz/9569680, special reminder, download to 1 points oh.

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.

Related Article

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.