import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FileDownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String FILE_PATH = "/path/to/your/file.ext"; // 文件的绝对路径
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
File file = new File(FILE_PATH);
if (file.exists()) {
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
response.setContentLength((int) file.length());
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
response.getOutputStream().write(buffer, 0, bytesRead);
}
fis.close();
response.getOutputStream().flush();
} else {
response.getWriter().println("File not found.");
}
}
}
谢谢,这个是chatgpt给出的、用HttpServletResponse 实现的 下载代码。可是这样写以后,供前端下载的请求url 是什么呢?谢谢
【 在 CHNSTAR 的大作中提到: 】
: 不用Spring框架提供的封装类
: 直接用原始的Servlet API
: 反正Spring最后调用的还是HttpServletResponse
: ...................
--
FROM 120.242.238.*