项目目录:
servletdemo3.java源码:
package com.haidi8.servlet;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class servletdemo3 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//通过路径得到一个输入流
String path=this.getServletContext().getRealPath("/WEB-INF/classes/美女.jpg");
FileInputStream fis =new FileInputStream(path);
//创建字节输出流
ServletOutputStream os=response.getOutputStream();
//得到要下载的文件名
String filename=path.substring(path.lastIndexOf("\\")+1);
//设置文件名的编码
filename=URLEncoder.encode(filename, "utf-8");//将不安全的文件名改为utf-8的形式
//告知客户端要下载文件
response.setHeader("content-disposition", "attachment;filename="+filename);
response.setHeader("content-type", "image/jpeg");
//执行输出操作
int len=1;
byte[] b=new byte[1024];
while((len=fis.read(b))!=-1){
os.write(b);
}
os.close();
fis.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
web.xml源码:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name></display-name>
<servlet>
<servlet-name>servletdemo3</servlet-name>
<servlet-class>com.haidi8.servlet.servletdemo3</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servletdemo3</servlet-name>
<url-pattern>/servletdemo3</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
结果:
刷新即下载。