package org.servlet.demo;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 测试在servlet中,发送请求 下载图片
*
* @author k.sea
*
*/
public class DownLoadImageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// 获取当前目录的图片路径
// String path=this.getServletContext().getRealPath("/image/tuxing.png");
String path=this.getServletContext().getRealPath("/image/水星.png");
// 获取文件名
String fileName=path.substring(path.lastIndexOf("\\")+1);
System.out.println(fileName);
//制定浏览器头
//在下载的时候这里是英文是没有问题的
//resp.setHeader("content-disposition", "attachment;fileName="+fileName);
//如果图片名称是中文需要设置转码
resp.setHeader("content-disposition", "attachment;fileName="+URLEncoder.encode(fileName, "UTF-8"));
InputStream reader = null;
OutputStream out = null;
byte[] bytes = new byte[1024];
int len = 0;
try {
// 读取文件
reader = new FileInputStream(path);
// 写入浏览器的输出流
out = resp.getOutputStream();
while ((len = reader.read(bytes)) > 0) {
out.write(bytes, 0, len);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
if (out != null)
out.close();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(req, resp);
}
}