1. 程式人生 > >servlet頁面的圖片輸出和下載

servlet頁面的圖片輸出和下載

輸出圖片

package ImageBuffer;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.sun.org.apache.commons.collections.Buffer;
public class ImageDisplay extends HttpServlet {

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


response.setHeader("context-type", "image/jpeg");
InputStream in = 
this.getServletContext()
.getResourceAsStream("images/java.jpg");   //讀取目錄images下的java.jpg檔案 ,得到輸入流

byte buffer[]=new byte[1024];
int len = 0;

OutputStream out = response.getOutputStream();   //得到輸出流

while ((len=in.read(buffer))>0) {
out.write(buffer, 0, len);  //將圖片輸出到瀏覽器
}
}

}

  目錄檔案


輸出效果

下載圖片

將以上程式碼的response.setHeader部分改為以下

response.setHeader("content-disposition", "attachment;filename=Java.jpg"); 

執行程式碼,即可以Java.jpg為預設檔名下載圖片


如截圖所示