import javax.servlet.ServletContext;
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.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
/**
* WebServlet文件下载
* @author silence
*/
@WebServlet("/DownLoadServlet")
public class DownLoadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获得前端传入的文件名
String fleName = req.getParameter("fleName");
System.out.println("前端传入的文件名:" + fleName);
//获得servletContext对象
ServletContext context = getServletContext();
//设置响应的文件类型
resp.setHeader("content-type", context.getMimeType(fleName));
String newFileName = URLEncoder.encode(fleName, "utf-8");
//设置响应的文件名
resp.setHeader("content-disposition", "attachment" + newFileName);
//流传输
ServletOutputStream out = resp.getOutputStream();
FileInputStream input = new FileInputStream(context.getRealPath("/resources/" + fleName));
byte[] bytes = new byte[1024];
int len = -1;
while ((len = input.read(bytes)) != -1) {
out.write(bytes, 0, len);
}
input.close();
}
}
WebServlet文件下载
最新推荐文章于 2024-08-30 23:43:57 发布