Servlet實現將圖片寫入到網頁和實現圖片下載的功能

package donghongyujava.servlet;
 
import java.io.File;
 
public class ShowImage extends HttpServlet {
 
    /**
     * Constructor of the object.
     */
    public ShowImage() {
        super();
    }
 
    /**
     * Destruction of the servlet. <br>
     */
    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);
    }
 
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章