javaweb使用绝对路径实现获取本地文件下载到本地其他文件夹 jsp代码 servlet代码
时间: 2024-03-07 17:46:47 浏览: 158
好的,下面是实现该功能的 JSP 代码和 Servlet 代码:
JSP 代码:
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文件下载</title>
</head>
<body>
<h2>文件下载</h2>
<form action="downloadFile" method="post">
<input type="text" name="filePath" placeholder="请输入文件路径">
<br><br>
<input type="text" name="savePath" placeholder="请输入保存路径">
<br><br>
<input type="submit" value="下载">
</form>
</body>
</html>
```
Servlet 代码:
```java
package com.example.servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletContext;
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("/downloadFile")
public class DownloadFileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获取文件路径和保存路径
String filePath = request.getParameter("filePath");
String savePath = request.getParameter("savePath");
// 获取文件对象
File file = new File(filePath);
// 设置响应头
ServletContext context = getServletContext();
String mimeType = context.getMimeType(file.getAbsolutePath());
if (mimeType == null) {
mimeType = "application/octet-stream";
}
response.setContentType(mimeType);
response.setContentLength((int) file.length());
// 设置响应头,让浏览器下载文件
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", file.getName());
response.setHeader(headerKey, headerValue);
// 将文件输出到浏览器
try (FileInputStream in = new FileInputStream(file);
OutputStream out = response.getOutputStream()) {
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
}
// 将文件保存到本地
File saveFile = new File(savePath);
file.renameTo(saveFile);
}
}
```
注意事项:
1. 绝对路径必须以 “/” 开头;
2. 为了避免中文文件名乱码,需要设置响应头;
3. 文件输出到浏览器的同时,也将文件保存到本地。
阅读全文