ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
![](https://box.kancloud.cn/9b4db9aed052c69b9cfc2bf395dc5b95_627x198.png) DownloadServlet.java ~~~ package zyw.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.FileInputStream; import java.io.IOException; import java.io.InputStream; @WebServlet(name = "DownloadServlet",urlPatterns = "/download") public class DownloadServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //如何将服务器上的资源返回给浏览器 //response.getOutputStream();//输出二进制文件的 //response.getWriter();//输出字节码文件的 String filename=request.getParameter("filename"); //String filenameEncoder = URLEncoder.encode(filename, "utf-8"); //如何通知浏览器不要预览,而是下载文件 String mimeType = this.getServletContext().getMimeType(filename); response.setContentType(mimeType); response.setHeader("Content-Disposition","attachment;filename="+filename); //response.setHeader("Content-Disposition","attachment;filename="+filenameEncoder); //通过ServletContext对象获取文件的绝对路径 String realPath = this.getServletContext().getRealPath("download/"+filename); InputStream in =new FileInputStream(realPath);//输入流传入文件 ServletOutputStream outputStream = response.getOutputStream();//输出二进制文件的 //文件拷贝 int len=0; byte[] buffer=new byte[1024]; while ((len=in.read(buffer))>0){ outputStream.write(buffer,0,len); } in.close(); } } ~~~ ![](https://box.kancloud.cn/91211b3d93c827ceedcad437caf15a17_478x353.png)