一、新增專案依賴(gradle)
dependencies {
compile group: `javax.servlet`, name: `javax.servlet-api`, version: `3.1.0`
compile group: `commons-fileupload`, name: `commons-fileupload`, version: `1.3.3`
compile group: `javax.servlet`, name: `jstl`, version: `1.2`
}
二、上傳servlet
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
public class UploadServlet extends HttpServlet {
// 上傳檔案儲存目錄
private static final String UPLOAD_DIRECTORY = "upload";
// 上傳配置 上傳檔案最大值
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 檢測是否為多媒體上傳
if (!ServletFileUpload.isMultipartContent(request)) {
// 如果不是則停止
PrintWriter writer = response.getWriter();
writer.println("Error: 表單必須包含 enctype=multipart/form-data");
writer.flush();
return;
}
// 配置上傳引數
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
// 設定最大檔案上傳值
upload.setFileSizeMax(MAX_FILE_SIZE);
// 中文處理
upload.setHeaderEncoding("UTF-8");
// 構造臨時路徑來儲存上傳的檔案
// 這個路徑相對當前應用的目錄
String uploadPath = request.getServletContext().getRealPath("./") + File.separator + UPLOAD_DIRECTORY;
// 如果目錄不存在則建立
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
List<Map<String, String>> data = new ArrayList<>();
try {
// 解析請求的內容提取檔案資料
List<FileItem> formItems = upload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
// 迭代表單資料
for (FileItem item : formItems) {
// 處理不在表單中的欄位
if (!item.isFormField()) {
String fileName = item.getName();
String filePath = uploadPath + File.separator + UUID.randomUUID() + fileName;
File storeFile = new File(filePath);
// 在控制檯輸出檔案的上傳路徑
System.out.println(filePath);
// 儲存檔案到硬碟
item.write(storeFile);
data.add(new HashMap<String, String>() {{
put("name", fileName);
put("path", filePath);
}});
}
}
}
request.getSession().setAttribute("list", data);
request.setAttribute("message", "檔案上傳成功!");
} catch (Exception ex) {
request.setAttribute("message", "錯誤資訊: " + ex.getMessage());
}
// 跳轉到 message.jsp
request.getServletContext().getRequestDispatcher("/message.jsp").forward(request, response);
}
}
三、下載servlet
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
public class DownloadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String path = request.getParameter("path");
//處理請求
//讀取要下載的檔案
File f = new File(path);
if (f.exists()) {
FileInputStream fis = new FileInputStream(f);
String filename = URLEncoder.encode(f.getName(), "utf-8"); //解決中文檔名下載後亂碼的問題
byte[] b = new byte[fis.available()];
fis.read(b);
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition", "attachment; filename=" + filename + "");
//獲取響應報文輸出流物件
ServletOutputStream out = response.getOutputStream();
//輸出
out.write(b);
out.flush();
out.close();
}
}
}
四、配置web.xml
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4">
<servlet>
<servlet-name>uploadServlet</servlet-name>
<servlet-class>stu.servlet.UploadServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>downloadServlet</servlet-name>
<servlet-class>stu.servlet.DownloadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>uploadServlet</servlet-name>
<url-pattern>/uploadServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>downloadServlet</servlet-name>
<url-pattern>/downloadServlet</url-pattern>
</servlet-mapping>
</web-app>
五、上傳的jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<h1>檔案上傳</h1>
<form method="post" action="/uploadServlet" enctype="multipart/form-data">
選擇一個檔案:
<input type="file" name="uploadFile"/>
<br/><br/>
<input type="submit" value="上傳"/>
</form>
</body>
</html>
六、下載的jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${message}
<h1>檔案列表</h1>
<table>
<tbody>
<tr>
<td>檔案</td>
<td>下載</td>
</tr>
<c:forEach items="${list}" var="item">
<tr>
<td>${item.name}</td>
<td><a href="/downloadServlet?path=${item.path}">下載</a></td>
</tr>
</c:forEach>
</tbody>
</table>
</body>
</html>