创建web工程servlet,新建DownloadServlet.java
package com.xmyself.servlet; 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 doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { } public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/plain"); response.setHeader("Content-Disposition", "attachment; filename=test.jpg"); OutputStream outputStream = response.getOutputStream(); File file = new File("D:\\test.jpg"); 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 destroy() { } }
修改web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <display-name>servlet</display-name> <servlet> <servlet-name>download</servlet-name> <servlet-class>com.xmyself.servlet.DownloadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>download</servlet-name> <url-pattern>/download</url-pattern> </servlet-mapping> </web-app>
在D盘放置test.jpg文件,启动工程,浏览器访问
http://localhost:8080/servlet/download