要配置Tomcat服務器以允許文件下載,可以按照以下步驟進行操作:
<Context docBase="/path/to/download/directory" path="/downloads" />
<servlet>
<servlet-name>FileDownloadServlet</servlet-name>
<servlet-class>com.example.FileDownloadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileDownloadServlet</servlet-name>
<url-pattern>/downloads/*</url-pattern>
</servlet-mapping>
@WebServlet("/downloads/*")
public class FileDownloadServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String filePath = request.getPathInfo();
File file = new File("/path/to/download/directory" + filePath);
if (file.exists()) {
response.setContentType("application/octet-stream");
response.setContentLength((int) file.length());
response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
try (InputStream inputStream = new FileInputStream(file);
OutputStream outputStream = response.getOutputStream()) {
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
}
} else {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
}
}
http://localhost:8080/downloads/yourfile.txt
來下載文件。通過上述步驟,您可以配置Tomcat服務器以允許文件下載。請注意,為了安全起見,應該對下載文件的路徑和文件名進行驗證和過濾,以防止惡意文件下載。