package day08;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 案例【Content-Disposition】-- attachment; filename=aaa.zip
* @author Administrator
* 文件下载效果
*/
public class ResponseDemo05 extends HttpServlet {
private static final long serialVersionUID = 4407828089924059971L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*
request.setCharacterEncoding("utf-8");
response.setContentType("image/png;charset=utf-8");
// 1) 读取本地文件
FileInputStream in = new FileInputStream("e:/picture.png");
// 2) 写出给浏览器(字节内容)
OutputStream out = response.getOutputStream();
byte[] buf = new byte[1024];
int len = 0;
// 边读边写
while( (len=in.read(buf)) != -1) {
out.write(buf, 0, len);
}
// 关闭
in.close();
out.close();
*/
/**
* 但是我们是想让浏览器把这张图片以下载的方式打开
*/
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
File file = new File("e:/图片.png");// 中文的图片名的话,必须这样进行包装 先通过GBK进行getBytes,然后通过设置新的ISO8859_1
response.setHeader("content-disposition", "attachment;filename="+new String(file.getName().getBytes("GBK"),"ISO8859_1"));
// 1) 读取本地文件
FileInputStream in = new FileInputStream(file);
// 2) 写出给浏览器(字节内容)
OutputStream out = response.getOutputStream();
byte[] buf = new byte[1024];
int len = 0;
// 边读边写
while( (len=in.read(buf)) != -1) {
out.write(buf, 0, len);
}
// 关闭
in.close();
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
}
}