Servlet 实现文件下载
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
(value = "/down")
public class DownloadServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
String fileName = req.getParameter("file");
if (fileName == null) {
// 默认下载文件
fileName = "OOP.png";
}
// 防止文件泄露
fileName = fileName.replace("../", "");
String realPath = req.getServletContext().getRealPath("/WEB-INF/upload/" + fileName);
File downloadFile = new File(realPath);
// ros 不能放到 try-resources 中, 否则发生异常时无法正常输出 404
ServletOutputStream ros = resp.getOutputStream();
try (FileInputStream fis = new FileInputStream(downloadFile)) {
resp.addHeader("Content-Disposition", "attachment;filename="
+ downloadFile.getName());
int len = -1;
byte[] data = new byte[1024];
while ((len = fis.read(data)) != -1) {
ros.write(data, 0, len);
}
} catch (FileNotFoundException ignored) {
resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Image Not Found");
}
}
}