首页 > 代码库 > servlet文件下载
servlet文件下载
一、创建servlet
package com.demo.log4j; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class DownloadServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void init(ServletConfig config) throws ServletException { } public void doGet(HttpServletRequest req, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/plain"); response.setHeader("Content-Disposition", "attachment; filename=demo.docx"); OutputStream outputStream = response.getOutputStream(); File file = new File("D:\\demo.docx"); InputStream inputStream = null; try { inputStream = new FileInputStream(file); byte[] buffer = new byte[1024]; int i = -1; while ((i = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, i); } outputStream.flush(); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } } public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { } public void destroy() { } }
二、配置web.xml
<servlet> <servlet-name>download</servlet-name> <servlet-class>com.demo.log4j.DownloadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>download</servlet-name> <url-pattern>/download</url-pattern> </servlet-mapping>
三、下载文件
浏览器访问地址
http://127.0.0.1:8080/download
servlet文件下载
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。