package com.aib.soft;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class download extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse res)
throws ServletException, IOException {
//获取资源的绝对路径
String path = this.getServletContext().getRealPath("/image/gr.jpg");
//获取资源名
String filename = path.substring(path.lastIndexOf("\\") + 1);
// 以下载方式打开的响应头content-disposition,并用URLEncoder.encode方法转码
res.setHeader("content-disposition",
"attachment;filename="+URLEncoder.encode(filename,"UTF-8"));
//获取字节流(非文本资源必须用字节流)
OutputStream out = res.getOutputStream();
//文件输入流
InputStream in=new FileInputStream(path);
//向代表客户端的response输出资源
byte[] buf=new byte[1024];
int len=0;
while((len=in.read(buf))>0){
out.write(buf, 0, len);
}
//out.flush(); response由Servlet管理,可不关闭流
//out.close();
in.close(); // 由程序员自己管理
System.out.println("-------s");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}