当我们需要上传大文件或者一些二进制文件到服务器上的时候,需要使用文件上传功能。下面是在Servlet中实现文件上传的完整攻略:
1. 导入依赖
在pom.xml
文件中加入以下依赖:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.8.0</version>
</dependency>
2. 创建Servlet
创建一个Java类,继承HttpServlet
,用于处理文件上传的请求。在doPost
方法中,读取文件数据,并保存到指定的目录中。文件上传的主要过程如下:
- 创建
DiskFileItemFactory
对象,用于在内存中处理文件数据和获取FileItem
对象 - 创建
ServletFileUpload
对象,并设置文件的大小限制、请求编码、DiskFileItemFactory
对象等处理数据的参数 - 调用
parseRequest
方法,获取所有的文件项列表 - 遍历文件项列表,判断是否是上传文件,并获取文件的原始名称和数据
- 将文件数据写入指定的目录中
示例代码如下:
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String uploadPath = "/path/to/your/upload/folder";
int maxFileSize = 1024 * 1024 * 10; // 10MB
int maxMemSize = 1024 * 1024 * 1; // 1MB
String characterEncoding = "UTF-8";
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set the size threshold, above which content will be stored on disk
factory.setSizeThreshold(maxMemSize);
// Set the temporary directory to store the uploaded files of size above threshold
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setFileSizeMax(maxFileSize);
// Set overall request size constraint
upload.setSizeMax(1024 * 1024 * 50); //50MB
// Parse the request
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
// Check if the item is a file upload
if (!item.isFormField()) {
// Get the file name
String fileName = item.getName();
// Get the uploaded file's content type
String contentType = item.getContentType();
// Get the uploaded file data
byte[] fileData = item.get();
// Write the file data to the specified location
File uploadedFile = new File(uploadPath + File.separator + fileName);
item.write(uploadedFile);
out.println("File " + fileName + " has been uploaded successfully.");
out.println("<br>");
}
}
out.close();
}
}
3. 创建页面
在web.xml
文件中,配置Servlet和它的映射路径。然后创建一个html页面,用于选择要上传的文件。
示例代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>File Upload</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
h1, h2 {
text-align: center;
}
form {
width: 50%;
margin: 0 auto;
border: 2px solid #ccc;
padding: 20px;
text-align: center;
}
input[type="file"] {
font-size: 1.5em;
margin-top: 20px;
}
input[type="submit"] {
font-size: 1.5em;
margin-top: 20px;
background: #5cb85c;
color: #fff;
border: none;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
}
input[type="submit"]:hover {
background: #4cae4c;
}
</style>
</head>
<body>
<h1>File Upload Example</h1>
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<br>
<input type="submit" value="Upload">
</form>
</body>
</html>
4. 验证文件上传
启动应用,访问页面。在表单中选择要上传的文件,点击“Upload”按钮,即可将文件上传到服务器上。
另外一个示例:实现一个多文件上传的功能。步骤与上面基本相同,主要是在遍历文件项列表的时候,可以获取到多个文件项,并逐一处理。
public class MultipleFileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String uploadPath = "/path/to/your/upload/folder";
int maxFileSize = 1024 * 1024 * 10; // 10MB
int maxMemSize = 1024 * 1024 * 1; // 1MB
String characterEncoding = "UTF-8";
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(maxMemSize);
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(maxFileSize);
upload.setSizeMax(1024 * 1024 * 50); //50MB
try {
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
if (!item.isFormField()) {
String fileName = item.getName();
fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
String contentType = item.getContentType();
byte[] fileData = item.get();
File uploadedFile = new File(uploadPath + File.separator + fileName);
item.write(uploadedFile);
out.println("File " + fileName + " has been uploaded successfully.");
out.println("<br>");
}
}
out.println("<a href=\"multiple.html\">Upload more files</a>");
} catch (Exception ex) {
out.println("Error: " + ex.getMessage());
out.println("<br>");
out.println("<a href=\"multiple.html\">Try again</a>");
} finally {
out.close();
}
}
}
页面示例代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Multiple File Upload</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
h1, h2 {
text-align: center;
}
form {
width: 50%;
margin: 0 auto;
border: 2px solid #ccc;
padding: 20px;
text-align: center;
}
input[type="file"] {
font-size: 1.5em;
margin-top: 20px;
}
input[type="submit"] {
font-size: 1.5em;
margin-top: 20px;
background: #5cb85c;
color: #fff;
border: none;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
}
input[type="submit"]:hover {
background: #4cae4c;
}
</style>
</head>
<body>
<h1>Multiple File Upload Example</h1>
<form action="multiple" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload1" id="fileToUpload1">
<br>
<input type="file" name="fileToUpload2" id="fileToUpload2">
<br>
<input type="file" name="fileToUpload3" id="fileToUpload3">
<br>
<input type="submit" value="Upload">
</form>
</body>
</html>
要注意的是,在HTML页面中要添加一个enctype
属性,值为multipart/form-data
,以便能够正确接收文件上传的数据。另外,Servlet中需要解析请求的body部分,因此需要使用commons-fileupload
提供的API方法来读取数据。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:聊聊在Servlet中怎么上传文件 - Python技术站