在本文中,我将讨论如何在 servlet 中上传和下载文件到服务器。在本文的最后,您将了解如何在基于 Servlet 的 Java Web 应用程序中设置文件上传和文件下载功能。作为本示例的一部分,我们创建了以下文件:
- fileupload.jsp
- allfiles.jsp
- fileuploadResponse.jsp
- UploadDetail.java
- FileUploadServlet.java
- UploadedFileServlet.java
- FileDownloadServlet.java
- web.xml
- main.css
UploadDetail.java是一个 POJO 类,用于存储上传的文件状态,即文件名、文件状态和文件上传状态。FileUploadServlet.java是一个用于上传文件的控制器类。servlet 使用带有文件大小阈值、最大文件大小和最大请求大小的 @Multipartconfig 注释进行注释。UploadedFileServlet.java是一个控制器类,用于显示已经上传到服务器的文件。FileDownloadServlet.java用于从服务器下载文件。
fileupload.jsp页面包含上传单个文件或多个文件的上传表单。FileUploadResponse.jsp页面用于显示上传文件的结果。在这个JSP中,我们遍历uploadDetail对象列表,打印上传文件信息的表格数据。此外,在此页面上,我们创建了最后一列作为上传文件的下载链接。allfiles.jsp页面用于显示驻留在服务器上的文件总数的结果。web.xml是一个部署描述符,包含有关 servlet 的信息。main.css是用于描述文档外观和格式的样式表。
fileupload.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Servlet File Upload/Download</title>
<link rel="stylesheet" href="resource/css/main.css" />
</head>
<body>
<div class="panel">
<h1>File Upload</h1>
<h3>Press 'CTRL' Key+Click On File To Select Multiple Files in Open Dialog</h3>
<form id="fileUploadForm" method="post" action="fileUploadServlet" enctype="multipart/form-data">
<div class="form_group">
<label>Upload File</label><span id="colon">: </span><input id="fileAttachment" type="file" name="fileUpload" multiple="multiple" />
<span id="fileUploadErr">Please Upload A File!</span>
</div>
<button id="uploadBtn" type="submit" class="btn btn_primary">Upload</button>
</form>
</div>
<!-- List All Uploaded Files -->
<div class="panel">
<a id="allFiles" class="hyperLink" href="<%=request.getContextPath()%>/uploadedFilesServlet">List all uploaded files</a>
</div>
</body>
</html>
allfiles.jsp
<%@page import="java.util.List"%>
<%@page import="com.jcg.servlet.UploadDetail"%>
<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Servlet File Upload/Download</title>
<link rel="stylesheet" href="resource/css/main.css" />
</head>
<body>
<div class="panel">
<h1>Uploaded Files</h1>
<table class="bordered_table">
<thead>
<tr align="center"><th>File Name</th><th>File Size</th><th>Action</th></tr>
</thead>
<tbody>
<% List<UploadDetail> uploadDetails = (List<UploadDetail>) request.getAttribute("uploadedFiles");
if (uploadDetails != null && uploadDetails.size() > 0) {
for (int i = 0; i < uploadDetails.size(); i++) {
%>
<tr>
<td align="center"><span id="fileName"><%=uploadDetails.get(i).getFileName()%></span></td>
<td align="center"><span id="fileSize"><%=uploadDetails.get(i).getFileSize()%> KB</span></td>
<td align="center"><span id="fileDownload"><a id="downloadLink" class="hyperLink" href="<%=request.getContextPath()%>/downloadServlet?fileName=<%=uploadDetails.get(i).getFileName()%>">Download</a></span></td>
</tr>
<% }
} else { %>
<tr>
<td colspan="3" align="center"><span id="noFiles">No Files Uploaded.....!</span></td>
</tr>
<% }%>
</tbody>
</table>
<div class="margin_top_15px">
<a id="fileUpload" class="hyperLink" href="<%=request.getContextPath()%>/fileupload.jsp">Back</a>
</div>
</div>
</body>
</html>
fileuploadResponse.jsp
<%@page import="java.util.List"%>
<%@page import="com.servlet.UploadDetail"%>
<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Servlet File Upload/Download</title>
<link rel="stylesheet" href="resource/css/main.css" />
</head>
<body>
<div class="panel">
<h1>File Upload Status</h1>
<table class="bordered_table">
<thead>
<tr align="center"><th>File Name</th><th>File Size</th><th>Upload Status</th><th>Action</th></tr>
</thead>
<tbody>
<% List<UploadDetail> uploadDetails = (List<UploadDetail>) request.getAttribute("uploadedFiles");
for (int i = 0; i < uploadDetails.size(); i++) {
%>
<tr>
<td align="center"><span id="fileName"><%=uploadDetails.get(i).getFileName()%></span></td>
<td align="center"><span id="fileSize"><%=uploadDetails.get(i).getFileSize()%> KB</span></td>
<td align="center"><span id="fileuploadStatus"><%=uploadDetails.get(i).getUploadStatus()%></span></td>
<td align="center"><span id="fileDownload"><a id="downloadLink" class="hyperLink" href="<%=request.getContextPath()%>/downloadServlet?fileName=<%=uploadDetails.get(i).getFileName()%>">Download</a></span></td>
</tr>
<% }%>
</tbody>
</table>
<div class="margin_top_15px">
<a id="fileUpload" class="hyperLink" href="<%=request.getContextPath()%>/fileupload.jsp">Back</a>
</div>
</div>
</body>
</html>
UploadDetail.java
package com.servlet;
import java.io.Serializable;
public class UploadDetail implements Serializable {
private long fileSize;
private String fileName, uploadStatus;
private static final long serialVersionUID = 1L;
public long getFileSize() {
return fileSize;
}
public void setFileSize(long fileSize) {
this.fileSize = fileSize;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getUploadStatus() {
return uploadStatus;
}
public void setUploadStatus(String uploadStatus) {
this.uploadStatus = uploadStatus;
}
}
FileUploadServlet.java
package com.servlet;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
@WebServlet(description = "Upload File To The Server", urlPatterns = {"/fileUploadServlet"})
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 10, maxFileSize = 1024 * 1024 * 30, maxRequestSize = 1024 * 1024 * 50)
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public static final String UPLOAD_DIR = "uploadedFiles";
/**
* *** This Method Is Called By The Servlet Container To Process A 'POST'
* Request ****
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
handleRequest(request, response);
}
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/**
* *** Get The Absolute Path Of The Web Application ****
*/
String applicationPath = getServletContext().getRealPath(""),
uploadPath = applicationPath + File.separator + UPLOAD_DIR;
File fileUploadDirectory = new File(uploadPath);
if (!fileUploadDirectory.exists()) {
fileUploadDirectory.mkdirs();
}
String fileName = "";
UploadDetail details = null;
List<UploadDetail> fileList = new ArrayList<UploadDetail>();
for (Part part : request.getParts()) {
fileName = extractFileName(part);
details = new UploadDetail();
details.setFileName(fileName);
details.setFileSize(part.getSize() / 1024);
try {
part.write(uploadPath + File.separator + fileName);
details.setUploadStatus("Success");
} catch (IOException ioObj) {
details.setUploadStatus("Failure : " + ioObj.getMessage());
}
fileList.add(details);
}
request.setAttribute("uploadedFiles", fileList);
RequestDispatcher dispatcher = request.getRequestDispatcher("/fileuploadResponse.jsp");
dispatcher.forward(request, response);
}
/**
* *** Helper Method #1 - This Method Is Used To Read The File Names ****
*/
private String extractFileName(Part part) {
String fileName = "",
contentDisposition = part.getHeader("content-disposition");
String[] items = contentDisposition.split(";");
for (String item : items) {
if (item.trim().startsWith("filename")) {
fileName = item.substring(item.indexOf("=") + 2, item.length() - 1);
}
}
return fileName;
}
}
UploadedFilesServlet.java
package com.servlet;
import com.servlet.UploadDetail;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(description = "List The Already Uploaded Files", urlPatterns = {"/uploadedFilesServlet"})
public class UploadedFilesServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public static final String UPLOAD_DIR = "uploadedFiles";
/**
* *** This Method Is Called By The Servlet Container To Process A 'GET'
* Request ****
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
handleRequest(request, response);
}
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/**
* *** Get The Absolute Path Of The Web Application ****
*/
String applicationPath = getServletContext().getRealPath(""),
uploadPath = applicationPath + File.separator + UPLOAD_DIR;
File fileUploadDirectory = new File(uploadPath);
if (!fileUploadDirectory.exists()) {
fileUploadDirectory.mkdirs();
}
UploadDetail details = null;
File[] allFiles = fileUploadDirectory.listFiles();
List<UploadDetail> fileList = new ArrayList<UploadDetail>();
for (File file : allFiles) {
details = new UploadDetail();
details.setFileName(file.getName());
details.setFileSize(file.length() / 1024);
fileList.add(details);
}
request.setAttribute("uploadedFiles", fileList);
RequestDispatcher dispatcher = request.getRequestDispatcher("/allfiles.jsp");
dispatcher.forward(request, response);
}
}
FileDownloadServlet.java
package com.servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
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;
@WebServlet(description = "Download File From The Server", urlPatterns = {"/downloadServlet"})
public class FileDownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public static int BUFFER_SIZE = 1024 * 100;
public static final String UPLOAD_DIR = "uploadedFiles";
/**
* *** This Method Is Called By The Servlet Container To Process A 'GET'
* Request ****
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
handleRequest(request, response);
}
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/**
* *** Get The Absolute Path Of The File To Be Downloaded ****
*/
String fileName = request.getParameter("fileName"),
applicationPath = getServletContext().getRealPath(""),
downloadPath = applicationPath + File.separator + UPLOAD_DIR,
filePath = downloadPath + File.separator + fileName;
File file = new File(filePath);
OutputStream outStream = null;
FileInputStream inputStream = null;
if (file.exists()) {
/**
* ** Setting The Content Attributes For The Response Object ***
*/
String mimeType = "application/octet-stream";
response.setContentType(mimeType);
/**
* ** Setting The Headers For The Response Object ***
*/
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", file.getName());
response.setHeader(headerKey, headerValue);
try {
/**
* ** Get The Output Stream Of The Response ***
*/
outStream = response.getOutputStream();
inputStream = new FileInputStream(file);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
/**
* ** Write Each Byte Of Data Read From The Input Stream Write
* Each Byte Of Data Read From The Input Stream Into The Output
* Stream ***
*/
while ((bytesRead = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
} catch (IOException ioExObj) {
System.out.println("Exception While Performing The I/O Operation?= " + ioExObj.getMessage());
} finally {
if (inputStream != null) {
inputStream.close();
}
outStream.flush();
if (outStream != null) {
outStream.close();
}
}
} else {
/**
* *** Set Response Content Type ****
*/
response.setContentType("text/html");
/**
* *** Print The Response ****
*/
response.getWriter().println("<h3>File " + fileName + " Is Not Present .....!</h3>");
}
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>Servlet File Upload/Download</display-name>
<welcome-file-list>
<welcome-file>fileupload.jsp</welcome-file>
</welcome-file-list>
</web-app>
main.css
* {
box-sizing: border-box;
}
.margin_top_15px {
margin-top: 15px;
}
.panel {
display: block;
padding: 15px;
border: 1px solid #c0c0c0;
width: 849px;
margin: 52px 0px 0px 32px;
}
label {
display: inline-block;
margin-bottom: 5px;
}
.form_group {
margin: 10px;
}
.btn_primary {
color: #fff;
background-color: #0275d8;
border-color: #0275d8;
}
.btn {
display: inline-block;
padding: 10px;
text-align: center;
white-space: nowrap;
vertical-align: middle;
cursor: pointer;
border: 1px solid transparent;
}
.input_error {
color: #DE3330;
padding: 5px;
}
.bordered_table {
border-collapse: collapse;
width: 100%;
table-layout: fixed;
}
.bordered_table tr,th,td {
border: 1px solid #333;
}
.bordered_table th,td {
padding: 5px;
}
.bordered_table td {
word-wrap: break-word;
}
#noFiles {
color: red;
font-size: larger;
}
.hyperLink {
text-decoration: none;
cursor: pointer;
}
Output
运行您的代码以获得以下输出。点击“选择文件”,选择要上传的文件,然后点击“上传”按钮。单击“列出所有上传的文件”链接以查看已上传文件的列表。
单击“上传”按钮后,您将收到以下响应。按“返回”链接返回文件上传页面。
单击“列出所有上传的文件”链接后,您将收到以下响应。单击“下载”链接以下载特定文件。
下载特定文件后,您将在此 PC -> 下载选项中找到该文件。
在本文中,我们开发了一个在 servlet 中上传和上传文件到服务器的应用程序,希望您喜欢这篇如何在 servlet 中上传和下载文件到服务器的文章。