在Java Web中,可以使用Servlet來處理文件下載請求。以下是一個簡單的示例,展示了如何使用Servlet實現文件下載功能:
FileDownloadServlet
,并繼承HttpServlet
類。重寫doGet
方法來處理文件下載請求。import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FileDownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 設置文件名和文件類型
String fileName = "example.txt";
String contentType = "text/plain";
// 設置響應頭信息
response.setContentType(contentType);
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
response.setContentLength((int) new File(fileName).length());
// 讀取文件并寫入到響應輸出流中
try (InputStream inputStream = new FileInputStream(fileName);
OutputStream outputStream = response.getOutputStream()) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
}
}
}
web.xml
文件中配置Servlet映射,將請求路徑(例如/download
)映射到FileDownloadServlet
。<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>FileDownloadServlet</servlet-name>
<servlet-class>FileDownloadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileDownloadServlet</servlet-name>
<url-pattern>/download</url-pattern>
</servlet-mapping>
</web-app>
http://localhost:8080/your-webapp-context/download
(請根據實際情況替換your-webapp-context
),將會觸發文件下載。注意:這個示例僅用于演示目的,實際應用中可能需要對文件類型、安全性等方面進行更嚴格的控制。