JavaWeb file upload and download methods

  • 2020-04-01 04:35:17
  • OfStack

File upload overview

Implement in web development File upload The functions need to be completed as follows Second step operation :

Add the upload input to the web page

The data from the uploaded file is read in the servlet and saved to the local hard disk.

How to add upload input item in web page ?

< Input type = "file" > Tag is used to add input items of file upload in the web page. Note when setting input items of file upload:

1. The name property of the input entry must be set, otherwise the browser will not send the data of the uploaded file.

2. The form's enctype must be set to multipart/form-data. After setting this value, the browser will attach the file data to the body of the HTTP request message when uploading the file, and describe the uploaded file using MIME protocol to facilitate the receiver to analyze and process the uploaded data.

File upload overview

How to read file upload data in Servlet and save to local hard disk ?

The Request object provides a getInputStream method that reads the data submitted by the client. However, since users may upload multiple files at the same time, it is a very troublesome work to program directly read the uploaded data on the servlet side and parse out the corresponding file data separately.

For the convenience of the user process file upload data, Apache open source organization provides a used to handle file upload forms an open source component (Commons fileupload), the component performance is excellent, and its API is extremely easy to use and allows developers to easily realize the web file upload function, thus realize the file upload function in web development, often use Commons fileupload component implementation.

To upload files using the commons-fileupload component, you need to import the corresponding supporting jars of the component: commons-fileupload and commons-io. Commons-io is not part of the development jar file for the fileupload component, but the commons-fileupload component starts with version 1.1 and works with the support of the commons-io package.

The fileupload component workflow

Core API - DiskFileItemFactory

DiskFileItemFactory is the factory that creates the FileItem object.

Public void setSizeThreshold(int sizeThreshold) : sets the size of the memory buffer to 10K by default. When the uploaded file is larger than the buffer size, the fileupload component uploads the file using the temporary file cache.

Public void setRepository(java.io.file repository) : specifies a temporary directory for files. The default is system.getproperty ("java.io.tmpdir").

Public DiskFileItemFactory(int sizeThreshold, java.io.file repository) : constructor

Core API - ServletFileUpload

ServletFileUpload handles the uploaded file data and wraps each input item in the form into a FileItem object. Common methods are:

Boolean isMultipartContent(HttpServletRequest request) : determines whether the upload form is of type multipart/form-data

List parseRequest(HttpServletRequest request) : parses the request object, wraps each input item in the form into a fileItem object, and returns a List collection that holds all fileitems.

SetFileSizeMax (long fileSizeMax) : sets the maximum number of uploaded files
SetSizeMax (long sizeMax) : sets the maximum number of uploaded files
SetHeaderEncoding (java.lang.String encoding) : sets the encoding format
SetProgressListener (ProgressListener pListener)

File upload case

Implementation steps

1. Create the DiskFileItemFactory object, set the buffer size and temporary file directory
2. Use the DiskFileItemFactory object to create the ServletFileUpload object and set a size limit for uploading files.
. 3, call ServletFileUpload parseRequest method parses the request object, get a save a List of all uploaded content object.
4. Iterate over the list. Each time, a FileItem object is iterated, and its isFormField method is called to determine whether the file is uploaded or not

For normal form fields, the getFieldName and getString methods are called to get the field name and field value

To upload a file, the getInputStream method is called to get the data input stream, which reads the uploaded data.

Encoding file upload

Upload file handling details

Chinese file garbled code problem

You can call the setHeaderEncoding method of ServletUpLoader, or set the setCharacterEncoding attribute of request

Temporary file deletion problem

Due to file size beyond DiskFileItemFactory. SetSizeThreshold method set the size of memory buffer, Commons fileupload component will use temporary file upload data, so at the end of the program, be sure to call FileItem. Delete delete temporary files.

The call to the Delete method must occur after the stream has closed, or the file will be occupied and the Delete will fail.

File location

To keep the server secure, the uploaded files should be stored in the web-inf directory of the application, or in a directory not managed by the WEB server.

In order to prevent multiple users from uploading files with the same file name, which may lead to file overwriting, the file uploader should ensure that the uploaded file has a unique file name.

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

File download

Because the file to be downloaded can be any type of file, the contents of the file to be sent to the client should be treated as binary, so you should call the method to return the ServeltOutputStream object to write the file contents to the client.

Download the case

Walk through all the files in the upload directory to display to the user and allow the user to complete the download.


 Read all the files in a folder and store them in the collection List And then endures request In scope) ListFileServelt -- (displays a list of all files) Listfiles.jsp-----DownloaServlet.java
private String id;
private String savename; //Upload file name, file uuid name
private String realName; //The real name of the uploaded file
private String savepath; //Remember the location of the file
private Date uptime; //Upload time of file
private String description; //Description of document
private String username; //The heir
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
Stringrealname = 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"," The 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);
}
}

Related articles: