图片文件下载
package com.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
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;
import java.net.URLEncoder;
public class FileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1.要获取下载文件的路径
// String realPath = this.getServletContext().getRealPath("/1.png");
String realPath="D:\\IdeaProjects\\javaweb-02-servlet\\response\\src\\main\\resources\\美图.png";
// 2.下载的文件名是啥
String fileName=realPath.substring(realPath.lastIndexOf("//")+1);
//subString(a)是截取a开始到结束(包括a,字符串从0开始);subString(a,b)截取a-b的字符串,不包括b
// 3.设置想办法让浏览器能够支持下载我们需要的东西
resp.setHeader("Content-Disposition","attachement;filename="+URLEncoder.encode(fileName,"UTF-8"));
// 4.获取下载文件的输入流
FileInputStream is=new FileInputStream(realPath);
// 5.创建缓冲区
int len=0;
byte[] buffer=new byte[1024];
// 6.获取OutputStream对象
ServletOutputStream out=resp.getOutputStream();
// 7.将FileOutputStream流写入到buffer缓冲区,使用OutputStream将缓冲区中的数据输出到客户端
while ((len=is.read(buffer))>0){
out.write(buffer,0,len);
}
is.close();
out.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
}
}
<servlet>
<servlet-name>down</servlet-name>
<servlet-class>com.zhy.Servlet.FileServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>down</servlet-name>
<url-pattern>/down</url-pattern>
</servlet-mapping>