Servlet實現圖片展示和下載的代碼
0
import java.io.File;
public class ShowImage extends HttpServlet {
/**
* Constructor of the object.
*/
public ShowImage() {
super();
}
/**
* Destruction of the servlet.
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// showImage(request, response);
downlodeImage(request, response);
}
public void showImage(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 讀取方式
// response.setContentType("application/zip");
response.setContentType("image/jpeg");
// 獲取圖片絕對路徑
String path = this.getServletContext().getRealPath("/");
File file = new File(path + "/images/WIN_20131027_214421.JPG");
// 創建文件輸入流
FileInputStream is = new FileInputStream(file);
// 響應輸出流
ServletOutputStream out = response.getOutputStream();
// 創建緩沖區
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
is.close();
out.flush();
out.close();
}
public void downlodeImage(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 獲取圖片絕對路徑
String path = this.getServletContext().getRealPath("/");
File file = new File(path + "/images/WIN_20131027_214421.JPG");
//設置頭信息,內容處理的方式,attachment以附件的形式打開,就是進行下載,并設置下載文件的命名
response.setHeader("Content-Disposition","attachment;filename="+file.getName());
// 創建文件輸入流
FileInputStream is = new FileInputStream(file);
// 響應輸出流
ServletOutputStream out = response.getOutputStream();
// 創建緩沖區
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
is.close();
out.flush();
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}