Javaweb implementation of File upload and download method _java

Source: Internet
Author: User

File Upload Overview

To achieve web development in the file upload function, you need to complete the following two steps :

Add an upload entry to a Web page

Reads the data for the uploaded file in the servlet and saves it to the local hard disk.

How do I add an upload entry to a Web page?

<input type= the "file" > tag is used to add a file transfer entry on a Web page, and you should note when transferring entries on a file:

1, you must set the input entry of the Name property, otherwise the browser will not send data uploaded files.

2. The enctype of the form must be set to multipart/ Form-data. After setting this value, when the browser uploads the file, it will attach the file data to the HTTP request message body and use the MIME protocol to describe the uploaded file so as to facilitate the receiver to parse and process the uploaded data.

File Upload Overview

How do I read the file upload data in the servlet and save it to the local hard drive?

The Request object provides a getInputStream method that can be used to read data submitted by the client. However, because users may upload multiple files at the same time, directly read the upload data in the servlet side, and parse out the corresponding file data separately is a very troublesome work, example.

To facilitate user handling of file upload data, the Apache Open source organization provides an open source component (Commons-fileupload) for handling form file uploads, which has excellent performance and its API is extremely simple, allowing developers to easily implement Web file uploads. Therefore, the implementation of file uploading in web development is usually implemented using the Commons-fileupload component.

Using the Commons-fileupload component to implement file uploads, you need to import the appropriate support jar packages for the component: Commons-fileupload and Commons-io. Commons-io does not belong to the development jar file for the file upload component, but the Commons-fileupload component starts with version 1.1 and requires Commons-io package support when it works.

FileUpload Component Workflow

Core Api-diskfileitemfactory

Diskfileitemfactory is a factory that creates Fileitem objects, a common method of this factory class:

public void Setsizethreshold (int sizethreshold): Sets the size of the memory buffer, with a default value of 10K. When the upload file is larger than the buffer size, the FileUpload component uses the temporary file cache to upload the file.

public void Setrepository (Java.io.File repository): Specifies the temporary file directory, and the default value is System.getproperty ("Java.io.tmpdir").

Public diskfileitemfactory (int sizethreshold, Java.io.File repository): constructor

Core Api-servletfileupload

Servletfileupload is responsible for processing uploaded file data and encapsulating each entry in the form into a Fileitem object. Common methods are:

Boolean ismultipartcontent (HttpServletRequest request): Determine if the uploaded form is a multipart/form-data type

List parserequest (HttpServletRequest request): Parses the Request object, wraps each entry in the form into a Fileitem object, and returns a list collection that holds all fileitem.

Setfilesizemax (Long Filesizemax): Sets the maximum value of the uploaded file
Setsizemax (Long Sizemax): Sets the maximum amount of uploaded files
Setheaderencoding (java.lang.String encoding): Setting the encoding format
Setprogresslistener (Progresslistener Plistener)

File Upload case

Implementation steps

1. Create Diskfileitemfactory object, set buffer size and temp file directory
2. Create the Servletfileupload object using the Diskfileitemfactory object and set the size limit of the uploaded file.
3. Call the Servletfileupload.parserequest method to parse the request object and get a list object that holds all the uploaded content.
4, the list of iterations, each iteration of a Fileitem object, call its Isformfield method to determine whether the file is uploaded

is a normal form field, then the GetFieldName, GetString method is invoked to get the fields name and field values

To upload the file, call the getInputStream method to get the data input stream to read the uploaded data.

Code implementation File Upload

Handling details of uploaded files

Chinese file garbled problem

File name Chinese garbled problem, can call Servletuploader setheaderencoding method, or set request Setcharacterencoding property

Temporary file deletion problem

Because the file size exceeds the memory buffer size set by the Diskfileitemfactory.setsizethreshold method, the Commons-fileupload component saves the uploaded data using temporary files, so be sure to call Fileitem.delete when the program ends method to delete a temporary file.

The call to the Delete method must be after the stream has closed, otherwise the file consumption will occur, causing the deletion to fail.

File storage location

To ensure server security, upload files should be stored in the Web-inf directory of the application or in a directory that is not managed by the Web server.

To prevent multiple users from uploading files of the same file name, resulting in file coverage, file upload procedures should ensure that the upload file has a unique filename.

In order to prevent a single directory of too many files, affecting the speed of file reading and writing, processing upload files should be based on the total number of files uploaded, select the appropriate directory structure generation algorithm, will upload files distributed storage.

File download

Because the files to be downloaded can be of various types of files, the corresponding content should be treated as binary when the file is routed to the client, so the method should be called to return the Serveltoutputstream object to write the file contents to the client.

Download case

All files in the upload directory are displayed to the user and the user is allowed to complete the download.

(Read all the files under a folder, save them to the list in the collection, and save to the request scope) listfileservelt-(show all the file lists) listfiles.jsp-----Downloaservlet.java
Private String ID; Private String Savename; The name of the uploaded file, the UUID name of the file, private String realname; The real name of the uploaded file is private String Savepath; Remember the location of the file private Date uptime; File upload time private String description; Description of the file private String username;
Upload people listfileservlet package com.hbsi.servlet;
Import Java.io.File;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import Java.util.HashMap;
Import Java.util.Map;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Importjavax.servlet.http.HttpServletRequest;
Importjavax.servlet.http.HttpServletResponse; public class Listfileservlet Extendshttpservlet {publicvoid doget (httpservletrequest request, HttpServletResponse Response) Throwsservletexception, IOException {stringsavepath = This.getservletcontext (). Getrealpath ("/WEB-INF/
Upload ");
Mapmap = new HashMap ();
Listfiles (NewFile (Savepath), map); Request.setattribute ("Map ", map);
Request.getrequestdispatcher ("/listfile.jsp"). Forward (Request,response); } privatevoid listfiles (file file, map map) {if (File.isfile ()) {stringuuidname = File.getname ();//Uuid_a_1_3_3.txt STR
Ingrealname = uuidname.substring (Uuidname.indexof ("_") + 1);
Map.put (Uuidname,realname);
}else {file[]files = File.listfiles (); for (File f:files) {listfiles (F,MAP);}}}
Publicvoid DoPost (httpservletrequest request, httpservletresponse response) Throwsservletexception, IOException {
Doget (Request,response);
}} Downloadservlet package com.hbsi.servlet;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.IOException;
Import Java.io.OutputStream;
Import Java.io.PrintWriter;
Import Java.net.URLEncoder;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Importjavax.servlet.http.HttpServletRequest;
Importjavax.servlet.http.HttpServletResponse; public class Downloadservlet Extendshttpservlet {publicvoid doget (httpservletrequest request, HTTPservletresponse response) Throwsservletexception, IOException {stringfilename = request.getparameter ("filename");
Filename= New String (Filename.getbytes ("iso8859-1"), "Utf-8");
SYSTEM.OUT.PRINTLN (filename);
Stringsavepath = This.getfilesavepath (this.getrealname (filename));
Filef = new File (Savepath + "\" + filename); if (!f.exists ()) {Request.setattribute ("message", "downloaded resource does not exist"); Request.getrequestdispatcher ("/message.jsp").
Forward (Request,response); } response.setheader ("Content-disposition", "attachment;filename=" + urlencoder.encode this.getrealname (filename),
"UTF-8"));
Fileinputstreamin = new FileInputStream (f);
Byte[]buf = new byte[1024];
Intlen = 0;
Outputstreamout = Response.getoutputstream ();
while (len = In.read (buf)) > 0) {out.write (buf,0, Len);} in.close (); } publicstring Getfilesavepath (String filename) {intdir1 = Filename.hashcode () & 0xf; Intdir2 = (Filename.hashcode ()
>> 4) & 0xf; Stringsavepath = This.getservletcontext (). Getrealpath ("/web-inf/upload")+ "\" + Dir1 + "\" + Dir2;
Returnsavepath;
} publicstring getrealname (String filename) {stringrealname = filename.substring (Filename.indexof ("_") + 1);
Returnrealname;
} publicvoid DoPost (httpservletrequest request, httpservletresponse response) Throwsservletexception, IOException {
Doget (Request,response); }
}

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.