1. 程式人生 > >Java Servlet 向客戶端返回一個影象的方法(靜態)

Java Servlet 向客戶端返回一個影象的方法(靜態)

 一、伺服器端的靜態圖片。

1.1  基於ImageIO來實現。

public void getMap(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{

response.setContentType("image/png");

String path = "e:/maprequest.png";

BufferedImage bi = ImageIO.read(new File(path));

ImageIO.write(bi, "png", response.getOutputStream());

1.2基於FileInputStream 和OutputStream來實現

public void getMap(HttpServletRequest request, HttpServletResponse response)throws        ServletException, IOException{

try{ 

FileInputStream hFile = new FileInputStream("e:\\map.GIF"); // 以byte流的方式開啟檔案 d:\1.gif 

int i=hFile.available(); //得到檔案大小 

byte data[]=new byte[i]; 

hFile.read(data); //讀資料 

hFile.close(); 

response.setContentType("image/png"); //設定返回的檔案型別 

OutputStream toClient=response.getOutputStream(); //得到向客戶端輸出二進位制資料的物件 

toClient.write(data); //輸出資料 

toClient.close(); 

catch(IOException e) //錯誤處理 

PrintWriter toClient = response.getWriter(); //得到向客戶端輸出文字的物件 

response.setContentType("text/html;charset=UTF-8"); 

toClient.write("無法開啟圖片!"); 

toClient.close(); 

}