JavaEE文件上传和下载案例
时间: 2024-12-30 22:26:06 浏览: 10
### JavaEE 文件上传与下载
#### 文件上传示例代码
为了实现文件上传功能,在 `web.xml` 配置文件中定义了一个名为 `UploadServlet` 的 Servlet 来处理文件上传请求。此 Servlet 使用 Apache Commons FileUpload 库来解析 multipart/form-data 请求。
```java
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 设置编码方式
request.setCharacterEncoding("UTF-8");
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
if (!item.isFormField()) {
String fileName = FilenameUtils.getName(item.getName());
InputStream fileContent = item.getInputStream();
Path path = Paths.get("uploads", fileName);
Files.copy(fileContent, path, StandardCopyOption.REPLACE_EXISTING);
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h2>文件 " + fileName + " 已成功上传</h2>");
out.println("</body></html>");
}
}
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e.getCause());
}
}
}
```
上述代码展示了如何通过 `DiskFileItemFactory` 和 `ServletFileUpload` 解析并保存上传的文件[^1]。
#### 文件下载示例代码
对于文件下载操作,则可以通过创建另一个名为 `DownloadServlet` 的 Servlet 实现:
```java
@WebServlet("/download/*")
public class DownloadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String filePath = URLDecoder.decode(req.getPathInfo().substring(1), "UTF-8");
File downloadFile = new File(filePath);
FileInputStream inputStream = new FileInputStream(downloadFile);
// 获取 MIME 类型
String mimeType = getServletContext().getMimeType(filePath);
if (mimeType == null) {
mimeType = "application/octet-stream";
}
resp.setContentType(mimeType);
resp.setContentLength((int) downloadFile.length());
// 建议浏览器以附件形式下载该资源
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
resp.setHeader(headerKey, headerValue);
OutputStream outputStream = resp.getOutputStream();
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outputStream.close();
}
}
```
这段代码实现了从服务器端读取指定路径下的文件并通过 HTTP 响应返回给客户端的功能[^3]。
阅读全文