web下载文件设置的头信息
转:https://www.cnblogs.com/hackxiyu/p/9046247.html
使用web下载文件的时候,需要在实例化FileServlet 类的doGet方法里面添加以下设置
resp.setHeader(“Content-disposition”,“attachment;filename”+ URLEncoder.encode(filename,“UTF-8”));
主要代码:
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.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
public class FileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取下载文件的路径
String path = "/J:/code/maven/javaweb-02-servlet/reponse/target/classes/你好.jpg";
System.out.println("要下载的文件路径:"+path);
//下载文件名
String filename = path.substring(path.lastIndexOf("//") + 1);
//然浏览器支持下载
resp.setHeader("Content-disposition","attachment;filename"+ URLEncoder.encode(filename,"UTF-8"));
//获取文件下载的输入流
FileInputStream inst = new FileInputStream(path);
//创建缓冲区
int len = 0;
byte[] buffer = new byte[1024];
// 获取OutputStream
ServletOutputStream out = resp.getOutputStream();
// 建out放入缓冲区
while ((len=inst.read(buffer))!=-1){
out.write(buffer,0,len);
}
inst.close();
out.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
*xml配置:*
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">
<!-- 注册servlet -->
<servlet>
<servlet-name>filedown</servlet-name>
<servlet-class>com.pangiggs.servlet.FileServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>filedown</servlet-name>
<url-pattern>/dw</url-pattern>
</servlet-mapping>
</web-app>