package cn.base.servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.base.bean.BeanHelper;

@SuppressWarnings("serial")
public class ShowImagesServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		String fullPath;
		String localPath = request.getParameter("imagePath");
		String basePath = BeanHelper.getModuleConfFactory().getScatter().getBasePath(); //private.xml中读取文件存放路径
		fullPath = basePath + localPath; //图片的全路径
		
		FileInputStream fis = null;
		OutputStream toClient = null;
		
		try {
			fis = new FileInputStream(fullPath);
			int i = fis.available(); // 得到文件大小
			byte data[] = new byte[i];
			fis.read(data); // 读数据
			fis.close();
			response.setContentType("image/*"); // 设置返回的文件类型
			toClient = response.getOutputStream(); // 得到向客户端输出二进制数据的对象
			toClient.write(data); // 输出数据
			toClient.close();
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			//try中途发生异常后关闭所有IO流
			closeAllIO(toClient, fis);
		}
	}
	
	//关闭所有IO流
	private void closeAllIO(OutputStream toClient,FileInputStream fis) {
		try {
			if(toClient != null)
				toClient.close();
			if(fis != null) 
				fis.close();
		}catch(IOException e) {
			//iLog.error("IO关闭失败："+e);
		}
	}
}

