add<文件上传与下载>
parent
423a8962bb
commit
ddee3af2c1
|
@ -0,0 +1,57 @@
|
|||
package example.controller;
|
||||
|
||||
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("/download")
|
||||
public class FileDownloadServlet extends HttpServlet {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
// 设置文件上传路径(webapp/uploads)
|
||||
private static final String UPLOAD_DIRECTORY = "uploads";
|
||||
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response)
|
||||
throws ServletException, IOException {
|
||||
|
||||
// 动态解析 webapp/uploads 的路径
|
||||
String uploadPath = getServletContext().getRealPath("/") + UPLOAD_DIRECTORY;
|
||||
|
||||
// 获取请求的文件名
|
||||
String fileName = request.getParameter("file");
|
||||
if (fileName == null || fileName.isEmpty()) {
|
||||
response.getWriter().println("File parameter is missing");
|
||||
return;
|
||||
}
|
||||
|
||||
// 构造文件的完整路径
|
||||
File file = new File(uploadPath + File.separator + fileName);
|
||||
|
||||
// 检查文件是否存在
|
||||
if (!file.exists()) {
|
||||
response.getWriter().println("File not found: " + fileName);
|
||||
return;
|
||||
}
|
||||
|
||||
// 设置响应的内容类型
|
||||
response.setContentType(getServletContext().getMimeType(file.getName()));
|
||||
response.setContentLength((int) file.length());
|
||||
response.setHeader("Content-Disposition", "inline; filename=\"" + fileName + "\"");
|
||||
|
||||
// 读取文件并写入到响应输出流
|
||||
try (FileInputStream fis = new FileInputStream(file);
|
||||
OutputStream os = response.getOutputStream()) {
|
||||
byte[] buffer = new byte[4096];
|
||||
int bytesRead;
|
||||
while ((bytesRead = fis.read(buffer)) != -1) {
|
||||
os.write(buffer, 0, bytesRead);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,83 @@
|
|||
package example.controller;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
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.disk.DiskFileItemFactory;
|
||||
import org.apache.commons.fileupload.servlet.ServletFileUpload;
|
||||
|
||||
@WebServlet("/UploadServlet")
|
||||
public class UploadServlet extends HttpServlet {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
// 设置上传目录
|
||||
private static final String UPLOAD_DIRECTORY = "uploads";
|
||||
|
||||
// 上传配置
|
||||
private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
|
||||
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
|
||||
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB
|
||||
|
||||
protected void doPost(HttpServletRequest request, HttpServletResponse response)
|
||||
throws ServletException, IOException {
|
||||
|
||||
// 检查请求是否为多部分内容
|
||||
if (!ServletFileUpload.isMultipartContent(request)) {
|
||||
response.getWriter().println("Error: Form must have enctype=multipart/form-data.");
|
||||
return;
|
||||
}
|
||||
|
||||
// 配置上传参数
|
||||
DiskFileItemFactory factory = new DiskFileItemFactory();
|
||||
factory.setSizeThreshold(MEMORY_THRESHOLD);
|
||||
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
|
||||
|
||||
ServletFileUpload upload = new ServletFileUpload(factory);
|
||||
upload.setFileSizeMax(MAX_FILE_SIZE);
|
||||
upload.setSizeMax(MAX_REQUEST_SIZE);
|
||||
|
||||
// 构造上传路径
|
||||
String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
|
||||
|
||||
// 如果目录不存在,则创建
|
||||
File uploadDir = new File(uploadPath);
|
||||
if (!uploadDir.exists()) {
|
||||
uploadDir.mkdir();
|
||||
}
|
||||
|
||||
try {
|
||||
// 解析请求的内容
|
||||
@SuppressWarnings("unchecked")
|
||||
List<FileItem> formItems = upload.parseRequest(request);
|
||||
|
||||
if (formItems != null && formItems.size() > 0) {
|
||||
for (FileItem item : formItems) {
|
||||
// 处理非表单字段
|
||||
if (!item.isFormField()) {
|
||||
String fileName = new File(item.getName()).getName();
|
||||
String filePath = uploadPath + File.separator + fileName;
|
||||
File storeFile = new File(filePath);
|
||||
|
||||
// 保存文件到磁盘
|
||||
item.write(storeFile);
|
||||
|
||||
request.setAttribute("message", "文件上传成功: " + fileName);
|
||||
request.setAttribute("fileName",fileName);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
request.setAttribute("message", "错误信息: " + ex.getMessage());
|
||||
}
|
||||
|
||||
// 转发到 JSP 显示消息
|
||||
getServletContext().getRequestDispatcher("/msg.jsp").forward(request, response);
|
||||
}
|
||||
}
|
|
@ -28,6 +28,13 @@
|
|||
</c:if>
|
||||
</div>
|
||||
|
||||
<form action="UploadServlet" method="post" enctype="multipart/form-data">
|
||||
<label for="file">选择图片:</label>
|
||||
<input type="file" name="file" id="file" required>
|
||||
<button type="submit">上传</button>
|
||||
</form>
|
||||
|
||||
|
||||
|
||||
</body>
|
||||
</html>
|
|
@ -9,6 +9,11 @@
|
|||
<body>
|
||||
<h2>提示:</h2>
|
||||
<h3>${sessionScope.msg}</h3>
|
||||
<h3>${message}</h3>
|
||||
<!-- 动态生成图片标签 -->
|
||||
<c:if test="${not empty fileName}">
|
||||
<img src="/download?file=/${fileName}" alt="Uploaded Image" style="max-width: 100%; height: auto;">
|
||||
</c:if>
|
||||
<button onclick="window.history.back();">返回</button>
|
||||
|
||||
</body>
|
||||
|
|
Reference in New Issue