The java component commons fileupload implements file upload
- 2020-05-10 18:11:20
- OfStack
1. Required bags:
1, commons - fileupload - 1.2.1. jar:
Download address
http://commons.apache.org/downloads/download_fileupload.cgi
2, commons io - 1.4. jar:
Download address
http://commons.apache.org/downloads/download_io.cgi
2. Precautions:
In the form form, enctype="multipart/ form-data "
3. Code sample
1. jsp code:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>upload</title>
</head>
<body>
<form action="uploadServlet" method="post" enctype="multipart/form-data">
<table>
<caption> Upload the instance </caption>
<tr>
<td> The name </td>
<td>
<input type="text" name="name">
</td>
</tr>
<tr>
<td> age </td>
<td>
<input type="text" name="age">
</td>
</tr>
<tr>
<td> photo </td>
<td>
<input type="file" name="image">
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value=" submit ">
</td>
</tr>
</table>
</form>
</body>
</html>
2. UploadServlet code
package servlet;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;
import java.util.List;
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.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
/**
* upload servlet
* @author lisanlai
*
*/
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public UploadServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
// Set the character encoding to UTF-8, This supports the display of Chinese characters
response.setCharacterEncoding("UTF-8");
Writer o = response.getWriter();
/**
* In the first place to judge form the enctype Isn't it multipart/form-data
* And also judged form The submission method is not post
* Methods: isMultipartContent(request)
*/
if(ServletFileUpload.isMultipartContent(request)){
request.setCharacterEncoding("utf-8");
// instantiation 1 Hard disk file factory , Used to configure the upload component ServletFileUpload
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set the temporary folder where the files are stored. This folder should be real
File fileDir = new File("../webapps/fileupload/tmp/");
if(fileDir.isDirectory() && fileDir.exists()==false){
fileDir.mkdir();
}
factory.setRepository(fileDir);
// Set the maximum memory footprint
factory.setSizeThreshold(1024000);
// create ServletFileUpload object
ServletFileUpload sfu = new ServletFileUpload(factory);
sfu.setHeaderEncoding("utf-8");
// Set the maximum value of a single file byte
sfu.setFileSizeMax(102400000);
// The maximum sum of all uploaded files byte
sfu.setSizeMax(204800000);
List<FileItem> items = null;
try {
items = sfu.parseRequest(request);
}catch (SizeLimitExceededException e) {
System.out.println(" The file size exceeds the maximum ");
} catch(FileUploadException e) {
e.printStackTrace();
}
// achieve items The iterator
Iterator<FileItem> iter = items==null?null:items.iterator();
// The directory where the image is stored after upload
File images = new File("D:/upload/images/");
if(images.exists()==false){
images.mkdirs();
}
// The iteration items
while(iter!=null && iter.hasNext()){
FileItem item = (FileItem) iter.next();
// If it's a normal form field
if(item.isFormField()){
System.out.print(" Common form fields :");
System.out.print(new String(item.getFieldName()) + " ");
System.out.println(new String(item.getString("UTF-8")));
}
// File domain
else if(!item.isFormField()){
System.out.println(" The source image :" + item.getName());
String fileName = item.getName().substring(item.getName().lastIndexOf("\\"));
BufferedInputStream in = new BufferedInputStream(item.getInputStream());
// The file is stored in D:/upload/images directory , This directory also has to exist
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(new File(images.getAbsolutePath()+ fileName)));
Streams.copy(in, out, true);
o.write(" File uploaded successfully ");
}
}
}else {
System.out.println(" The form of enctype Type error ");
}
}
}
3, 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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>UploadTest</display-name>
<welcome-file-list>
<welcome-file>upload.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>UploadServlet</display-name>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>servlet.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/uploadServlet</url-pattern>
</servlet-mapping>
</web-app>
This article has been sorted into "Java upload operation skills summary", welcome to learn to read.