Sophomore 15th file upload and download

Posted by philweb on Mon, 03 Jan 2022 15:06:40 +0100

File upload and download

How to upload files

To realize the file upload function in web development, it usually needs to complete two steps: one is to add the upload input item in the web page, and the other is to read the data of the uploaded file in the Servlet and save it to the local hard disk.
Since most file uploads are submitted to the server in the form of forms, in order to realize the function of file upload in the program, first create a form page for submitting uploaded files. In the page, you need to use tags to add file upload input items to the Web page.
The following two points should be paid attention to in the use of labels.
1. The name attribute of the input entry must be set, otherwise the browser will not send the data of the uploaded file.
2. The method attribute of the form page must be set to post mode, and the enctype attribute must be set to "multipart / form data". The example code is as follows.
<% – specify the enctype attribute of the form data and the submission method –% >

<% -- specify the type of tag and the name of the file field --% > select upload file:
When the browser submits and uploads a file through a form, because the file data is attached to the HTTP request message body and described by MIME type (Multipurpose Internet mail extension type), the data submitted by the client can be read in the background by using the getlnputStream() method provided by the request object. However, because users may upload multiple files at the same time, it is very troublesome to read the uploaded data directly on the Servlet side and parse the corresponding file data respectively. In order to facilitate the processing of data uploaded by users, the Apache organization provides an open source component, commons fileUpload. This component can easily parse various form fields in "multipart / form data" type requests, upload one or more files, and limit the size of uploaded files. Its performance is very excellent and its use is extremely simple. It should be noted that when using the FilieUpload component, you need to import Commons ileuploadjar and Commons io JAR two JAR packages, which can be downloaded from the Apache official website "http:/lcommons.apache.org /" (after entering the website page, find Fieupload and I0 in the Components column of the table under Apache Commons Proper, and click enter to find the download link). The Fieupload component realizes the file upload function through serve.

API related to file upload

Fileltem interface

The Fileltem interface is implemented in the Commons fileUpload component. It is mainly used to encapsulate the data of a single form field element. A form field element corresponds to a Fileltem object. In the process of file upload, the common fileUpload component encapsulates each form field (including ordinary text form field and file field) in a Fileltem object
For ease of explanation, the implementation class of fileltem interface is called fileltem class. Fileltem class implements serializable interface. Therefore, serialization operation is supported. Many methods for obtaining form field elements are defined in fileltem class, as follows.

(1) boolean isFormField() method
The isFormField() method is used to determine whether the data encapsulated by the Fileltem class object is a common text form field or a one person file form field. If it is a common text form field, it returns true; otherwise, it returns false.
(2)String getName() method
The getName() method is used to obtain the file name in the file upload field. If the Fileltem class object corresponds to an ordinary text form field, the getName() method will return null; Otherwise, as long as the browser passes the field information of the file to the server, the getName() method will return a string type result, such as "C:Sunset.jpg".
It should be noted that the full path and name obtained from files uploaded through different browsers are different. For example, when users upload files using IE browser, they get the complete path "C:ASunset.jpg"; If you use other browsers, such as Firefox, you only get the file name without a path, such as "Sunsetjpg".
(3) String getFieldName() method
The getFieldName() method is used to obtain the value of the name attribute of the description header of the form field element, which is also the value of the name attribute of the form label. For example, "file1" in "name=file1".
(4) Void write (file) method
The write() method is used to save the body content saved in the Fileltem object to a specified file. If the main content in the Fileltem object is saved in a temporary file, the temporary file may be cleared after the method is successfully completed. In addition, this method can also write the contents of ordinary form fields to a file, but it is mainly used to save the uploaded file contents to the local file system.
(5) String getString() method
Definition form of.
The getSring() method is used to return the data stream content saved in the Fileltem object as a string. It has two overloaded public String getString()
public String gelString(java.lang.String encoding)
In the above overloaded two methods, the former uses the default character set encoding to convert the body content into a string, and the latter uses the character set encoding specified by the parameter to convert the body content into a string. It should be noted that if Chinese garbled code occurs when reading the contents of ordinary form field elements, please call the second getString() method and pass it the correct character set encoding name.
(6)String getContentType() method
The getContentType() method is used to obtain the type of uploaded file, that is, the value of the description header attribute "content type" of the form field element, such as "image/jpeg". If the Fileltem class object corresponds to an ordinary form field, the method will return null.
(7) boolean isInMemory() method
The isInMemory() method is used to determine whether the data content encapsulated by the Fileltem object is stored in memory or in a temporary file. If it is stored in memory, it returns true; otherwise, it returns false.
(8) void delete() method
The delete() method is used to empty the body content stored in the Fileltem class object. If the body content is saved in a temporary file, the delete() method will delete the temporary file. It should be noted that although the temporary files will be automatically cleared when the Fileltem object is collected by the garbage collector, the delete() method should be called in time to clear the temporary files, so as to free the system storage resources, so as to prevent the system from exceptions, resulting in the temporary files being permanently saved in the hard disk.
(9)InputStream getInputStream() method
The getinputStream() method returns the data content of the uploaded file in the form of a stream.
(10) long getSize() method
The getSize() method returns the size (in bytes) of the uploaded file.

DiskFileltemFactory class

The DiskFileltemFactory class is used to encapsulate each file in the request message entity into a separate Fileltem object. If the uploaded file is small, it will be saved directly in memory. If the uploaded file is large, it will be saved in the temporary folder of the disk in the form of temporary file. By default, the critical value for saving files in memory or hard disk temporary folder is 10240, that is, 10KB.

Construction method of DiskFileltemFactory class

DiskFileltemFactory() uses default thresholds and system temporary folders to construct file item factory objects
DiskFileltemFactory(int sizeThre
repository) uses parameters to specify thresholds and system temporary folders to construct file item factory objects.
(1)Fileltem createltem(String fieldName, String contentType,boolean isFormField, String fileName) method
This method is used to create the request message entity as an instance object of Fileltem type. It should be noted that this method is automatically called by the FileUpload component when parsing the request, which does not need our management.
(2)setSizeThreshold(int sizeThreshold) and getSizeThreshold() methods
The setSizeThreshold() method is used to set the threshold value of whether to save the uploaded file on disk as a temporary file. When the Apache file upload component parses the uploaded data, it needs to save the parsed data temporarily for further data processing. Since the memory space available to the Java virtual machine is limited, the file storage location needs to be determined according to the size of the uploaded file. For example, an 800MB file cannot be temporarily saved in memory. At this time, the Apache file upload component can save these data in the form of temporary files. However, if the uploaded file is very small, only 600KB, obviously saving it in memory is a better choice. In addition, the corresponding getSizeThreshold() method is used to obtain this critical value.
(3)setRepository(File repository) and getRepository() methods
If the size of the uploaded file is larger than the critical value set by the setSizeThreshold() method, you can use the setRepository() method to save the uploaded file in the specified directory in the form of temporary file. By default, the system default temporary file path is used, which can be obtained in the following ways.
System.getProperty("java.io.tmpdir")
In addition, the corresponding getRepository() method is used to obtain temporary files.

The common methods of the ServletFileltemFactory class are as follows.

(1)setsizemax(long sizemax) and getsizemax()
The setsizemax() method inherits from the fileuploadbase class and is used to set the maximum size of the entity content of the request message to prevent the client from uploading large files maliciously to waste the storage space of the server. The parameter sizeMax is in bytes. In addition, the corresponding gatSizeMax() method is used to read the maximum value allowed by the entity content of the request message.
(2) setfileSizeMax(long fileSizeMax) and getFileSizeMax() methods
The setFilieSizeMax() method inherits from the FieUploadBase class and is used to set the maximum size limit of a single uploaded file. To prevent the client from maliciously uploading large files to waste the storage space of the server. The parameter fleSizeMax is in bytes. In addition, the corresponding getFileSizeMax() method is used to obtain the maximum value allowed for a single uploaded file.

Code and achievement display

package cn.itcast.fileupload;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class DownloadServlet
 */
@WebServlet("/DownloadServlet")
public class DownloadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DownloadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		String filename=request.getParameter("filename");
		filename= new String (filename.getBytes("iso-8859-1"),"utf-8");
		String fileType= getServletContext().getMimeType(filename);
		response.addHeader("Content-Type",fileType);
		response.addHeader("Content-Disposition","attachment;filename");
		String folder="/download/";
		
		InputStream in = getServletContext().getResourceAsStream(folder+filename);
		OutputStream out= response.getOutputStream();
		
		byte[] buffer=new byte[1024];
		int len= 0;
		while((len=in.read(buffer))>0)
		out.write(buffer,0,len);
		in.close();
		out.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

package cn.itcast.fileupload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;



/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			response.setContentType("text/html;charset=utf-8");
			DiskFileItemFactory factory= new DiskFileItemFactory();
			File f= new File("C:\\Temp");
			if(!f.exists()) {
				f.mkdirs();
			}
			factory.setRepository(f);
			factory.setSizeThreshold(1024*1024);
			ServletFileUpload fileupload= new ServletFileUpload(factory);
			fileupload.setHeaderEncoding("utf-8");
			List<FileItem> fileitems= fileupload.parseRequest(request);
			for(FileItem fileitem:fileitems) {
					boolean flag= fileitem.isFormField();
					if(flag) {
						String name= fileitem.getFieldName();
						if(name.equals("username")) {
							if(!fileitem.getString().equals("")) {
								String value = fileitem.getString("utf-8");
								response.getWriter().print("Uploaded by:"+value+"<br/>");
							}
						}
					}else {
						String filename= fileitem.getName();
						if(filename!=null&& !filename.equals("")) {
							response.getWriter().print("Uploaded file name:"+filename+"<br/>");
							filename=filename.substring(filename.lastIndexOf("\\")+1);
							filename=UUID.randomUUID().toString()+"_"+filename;
							String webPath="/upload2005/";
							String filepath=getServletContext().getRealPath(webPath+filename); 
							File file= new File(filepath);
							file.getParentFile().mkdirs();
							file.createNewFile();
							InputStream in= fileitem.getInputStream();
							FileOutputStream out= new FileOutputStream(file);
							byte[] buffer=new byte[1024];
							int len= 0;
							while((len=in.read(buffer))>0) {
								out.write(buffer,0,len);
						}
						in.close();
						out.close();
						fileitem.delete();
						response.getWriter().print("File uploaded successfully"+"<br/>");
					}
			}
		}
		
	}catch (FileUploadException e) {
	throw new RuntimeException(e);
  }
}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}




2020080605045 big data 2005 yuan Xuehua

Topics: Front-end Apache server