Java Web file upload and download __web

Source: Internet
Author: User
Tags create directory java web
In the Web application system development, the file uploads and the downloading function is the very commonly used function, today says the Javaweb file uploads and the downloading function realization.

For file upload, the browser upload the file in the form of streaming files to the server side, if the direct use of the servlet to obtain upload file input stream and then parse the request parameters inside is more trouble, So generally choose to use the Apache Open Source Tool common-fileupload This file upload component. This common-fileupload upload component jar package can go to the Apache online download, also can be found under the Lib folder of struts, struts upload function is based on this implementation. Common-fileupload is dependent on the Common-io package, so it is also necessary to download the package. One, the development environment constructs

Create a Fileuploadanddownload project, add the associated jar package for the Apache commons-fileupload File Upload component, as shown in the following illustration:

   Second, the implementation of file upload 2.1. File upload page and message prompt page

The code for the Upload.jsp page is as follows:

1 <%@ page language= "java" pageencoding= "UTF-8"%>
 2 <! DOCTYPE html>
 3 

The code for MESSAGE.JSP is as follows:

1 <%@ page language= "java" pageencoding= "UTF-8"%>
 2 <! DOCTYPE html>
 3 
2.2, processing file upload of the servlet

The code for Uploadhandleservlet is as follows:

  1 package Me.gacl.web.controller;
  2 3 Import Java.io.File;
  4 Import Java.io.FileOutputStream;
  5 Import java.io.IOException;
  6 Import Java.io.InputStream;
  7 Import Java.util.List;
  8 Import javax.servlet.ServletException;
 9 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; The public class Uploadhandleservlet extends HttpServlet {a public void doget (HttpServletRequest request, HttpServletResponse response) throws Servletexception, IOException {20//Get uploaded file to save directory, will upload Files are stored in the Web-inf directory, do not allow direct access to the outside world, to ensure the security of uploaded files String savepath = This.getservletcontext (). Getrealpath ("/web-inf/
 Upload ");
 File File = new file (Savepath); 23                Determine if there is a saved directory for uploaded files (!file.exists () &&!file.isdirectory ()) {25
 System.out.println (savepath+ "directory does not exist, needs to be created");
 26//Create directory File.mkdir ();
 28} 29//message hint String messages = ""; try{32///Use Apache File Upload component to process file upload steps: 33//1, create a diskfileitemfact
 Ory Factory Diskfileitemfactory factory = new Diskfileitemfactory ();
 35//2, create a file upload parser servletfileupload upload = new Servletfileupload (factory); 
 37//Resolution of the upload file name of Chinese garbled upload.setheaderencoding ("UTF-8"); 39//3, to determine whether the submitted data is uploaded form data of the IF (! Servletfileupload.ismultipartcontent (Request)) {41//Get data in traditional way retur
 N    43} 44                 4, using the Servletfileupload parser to parse the upload data, the result returned is a list<fileitem> collection, each fileitem corresponding to a form of the entry 45
 list<fileitem> list = upload.parserequest (request);                         for (Fileitem item:list) {47//if Fileitem encapsulates data for normal entries 48
 if (Item.isformfield ()) {The String name = Item.getfieldname (); 
 50//To solve the data of the ordinary entry of the Chinese garbled problem of a String value = item.getstring ("UTF-8");
 //value = new String (value.getbytes ("iso8859-1"), "UTF-8");
 SYSTEM.OUT.PRINTLN (name + "=" + value);                             }else{//If the Fileitem package is uploaded file 55//uploaded file name, 56
 String filename = Item.getname ();
 SYSTEM.OUT.PRINTLN (filename); if (Filename==null | | Filename.trim ().Equals ("")) {continue; 60} 61/Note: Different browsers submit the file name is not the same, some browsers submit the filename is a path, such as: c:\a\b\1.t XT, and some are just simple file names, such as: 1.txt 62///processing the path portion of the filename of the uploaded file to be obtained, leaving only the file name part
 Name = Filename.substring (Filename.lastindexof ("\") +1);
 64//Get the input stream of the uploaded file in the item inputstream in = Item.getinputstream (); 66//Create a file output stream FileOutputStream out = new FileOutputStream (SA
 Vepath + "\" + filename);
 68//Create a buffer in the byte buffer[] = new byte[1024];
 70//To determine whether the data in the input stream has been read out of the logo of int len = 0; 72//loop reads the input stream into the buffer, (len=in.read (buffer)) >0 indicates that there is data in it whil      E ((len=in.read (buffer)) >0) {74                           Writes the data of the buffer to the specified directory (Savepath + "\" + filename) using the FileOutputStream output stream 75
 Out.write (buffer, 0, Len);
 76} 77//Close input stream in.close ();
 79//Close output stream out.close ();
 81//delete processing file upload generated temporary files item.delete (); message = "File upload succeeded."
 ";                     }catch (Exception e) {87 message= "File upload failed.
 ";
 E.printstacktrace ();
 Request.setattribute ("message", message);
 Request.getrequestdispatcher ("/message.jsp"). Forward (request, response); The public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {doget (request, response); 99} 100}

Registering in the Web.xml file Uploadhandleservlet

1 <servlet>
2     <servlet-name>UploadHandleServlet</servlet-name>
3     < Servlet-class>me.gacl.web.controller.uploadhandleservlet</servlet-class>
4 </servlet>
5 
6 <servlet-mapping>
7     <servlet-name>UploadHandleServlet</servlet-name>
8     <url-pattern>/servlet/UploadHandleServlet</url-pattern>
9 </servlet-mapping>    

The operation effect is as follows:

After the file was uploaded successfully, the uploaded file was saved in the upload directory in the Web-inf directory, as shown in the following figure:

   2.3, the file upload details

Although the above code can successfully upload the file to the designated directory above the server, but the file upload function has a lot of attention to the small details of the problem, the following points need to pay special attention to

  1, in order to ensure server security, upload files should be placed in the outside can not directly access the directory, such as in the Web-inf directory.

2, in order to prevent the occurrence of file coverage, to upload files to produce a unique file name.

3. To prevent the occurrence of too many files under a directory, use the hash algorithm to break up the storage.

4, to limit the upload file maximum value.

5, to limit the type of upload file, when the upload file name, determine whether the suffix name is legitimate.

In response to the above 5 points of detail, we will improve the Uploadhandleservlet, the improved code is as follows:

  1

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.