首先在e盘放一张图片
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletDemo1 extends HttpServlet {
private static final long serialVersionUID = 1L;
public ServletDemo1() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/**
* 设置响应实体内容编码
*/
response.setCharacterEncoding("utf-8");
response.setContentType("image/jpg");//设置 响应的内容为imgage格式是jpg
File file = new File("e:/mm.jpg");
/**
* 设置以下载方式打开文件
*/
response.setHeader("Content-Disposition", "attachment; filename="+file.getName());
/**
* 下载图片
*//*
*//**
* 发送图片
*/
FileInputStream in = new FileInputStream(file);
byte[] buf = new byte[1024];
int len = 0;
//把图片内容写出到浏览器
while( (len=in.read(buf))!=-1 ){
response.getOutputStream().write(buf, 0, len);
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}