java 上传图片与图片读取

上传:

//获取参数文件流,并将文件流转化成二进制数组,适应JSP与Servlet

DiskFileItemFactory factory = new DiskFileItemFactory();

ServletFileUpload sfu = new ServletFileUpload(factory); sfu.setFileSizeMax(102400000); 

sfu.setSizeMax(204800000);  

List items = null; 

try { 

items = sfu.parseRequest(request); 

} catch (SizeLimitExceededException e) { 

System.out.println("size limit exception!"); 

} catch(Exception e) {  

e.printStackTrace(); 

Iterator iter = items==null?null:items.iterator(); 

while(iter != null && iter.hasNext()) {

FileItem item = (FileItem)iter.next();

if(item.isFormField()) {

System.out.print("form field:");

System.out.print(item.getFieldName() + " ");

System.out.print(item.getString()); 

}else if(!item.isFormField()) { 

System.out.println("client name:" + item.getName()); 

String fileName = item.getName();

//item.getInputStream() 获得文件流方法,其他文件不需要转化成二进制数组则不需要下面的转换

BufferedInputStream in = new BufferedInputStream(item.getInputStream());

byte[] b = new byte[in.available()];

in.read(b);

  }

}




下载:

读取java类:

import java.io.InputStream;
import java.math.BigDecimal;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.jdbc.datasource.DataSourceUtils;

import com.baosight.efmpx.system.sql.SqlID;
import com.baosight.efmpx.system.util.BeanContext;
import com.baosight.efmpx.system.util.ExceptionUtil;
import com.baosight.iplat4j.core.exception.PlatException;
import com.baosight.iplat4j.dao.ibatis.sqlmap.engine.impl.SqlMapClientImpl;
import com.ibatis.sqlmap.engine.mapping.parameter.ParameterMap;
import com.ibatis.sqlmap.engine.mapping.sql.Sql;
import com.ibatis.sqlmap.engine.mapping.sql.dynamic.DynamicSql;
import com.ibatis.sqlmap.engine.mapping.statement.MappedStatement;
import com.ibatis.sqlmap.engine.scope.RequestScope;


/**
 * @author danger
 *读取人员照片Dao
 */
public class EmpPhotoDao {

	//读取人员照片blob字段
	public static List<Map> readPhoto(Object param){
		
		DataSource ds = null;
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet resultSet = null;
		InputStream inputStream = null;
		List<Map> result = new ArrayList<Map>();
		try {
			SqlID sqlid = new SqlID("HREGEmpPhoto","readPhoto");
			SqlMapClientImpl client = BeanContext.getSqlMapClientImpl();
			/*取得查询语句*/
			MappedStatement statement = client.getMappedStatement(sqlid
					.getSqlID());
			/*取得ibatis sql对象*/
			Sql sql = statement.getSql();
			/*取得ibatis 参数map对象*/	
			ParameterMap parameterMap = null;
			RequestScope requestScope = new RequestScope();
			requestScope.setStatement(statement);
			
			if (sql instanceof DynamicSql/*动态sql*/) {
				parameterMap = sql.getParameterMap(requestScope, param);
			}else{
				parameterMap = statement.getParameterMap();
			}
			/*取得带参数的sql语句*/
			String s = sql.getSql(requestScope, param);
			//取得SQL连接对象
			ds = (DataSource)BeanContext.getBean("dataSource");
			con = ds.getConnection();
			ps = con.prepareStatement(s);
			if (parameterMap != null){		
				if(param instanceof Map){			
					parameterMap.setParameters(requestScope, ps, parameterMap.getParameterObjectValues(requestScope, param));
				}else{
					if(s.indexOf("?")>0){
						ps.setString(1, (String)param);
					}
				}
			}
			/*执行查询*/
			resultSet = ps.executeQuery();
			/*转换成目标对象*/
			Class c = statement.getResultMap().getResultClass();
			ResultSetMetaData rsm = resultSet.getMetaData();
			int columnCount = rsm.getColumnCount();
			while (resultSet.next()) {
				Map objMap = new HashMap();
				for (int i = 0; i < columnCount; i++) {
					if (resultSet.getObject(i + 1) instanceof Blob) {
						Blob blob = resultSet.getBlob(i + 1);
						Long length = blob.length();
						inputStream = blob.getBinaryStream();
						if(inputStream != null){
							byte [] bytes = new byte[length.intValue()];
							inputStream.read(bytes);
							objMap.put(rsm.getColumnName(i + 1), bytes);
						}
						inputStream.close();
					} else {	
						objMap.put(rsm.getColumnName(i + 1), resultSet.getObject(i + 1));
					}

				}
				result.add(objMap);
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw new PlatException(ExceptionUtil.getDB2CNMessage(e));
		}catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
            	if(ps!=null)
            		ps.close();
            	if(resultSet!=null)
            		resultSet.close();
                DataSourceUtils.doReleaseConnection(con, ds);
            } catch (SQLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                throw new PlatException(ExceptionUtil.getDB2CNMessage(e1));
            }
			return result;
		}	
		
	}
	
}



JSP将Blob 二进制数组转成图片


<%@page import="javax.servlet.jsp.tagext.TryCatchFinally"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%>
<%@ page import="*.EmpPhotoDao" %>
<%@ page import="java.util.Map" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="java.io.OutputStream" %>
<%@ page import="java.util.List" %>
<%

	OutputStream output = null;
	try{
		String empId = request.getParameter("empId");
		if(empId == null || empId.equals("")){
			return;
		}
		Map param = new HashMap();
		param.put("empId",empId);
		//调用java类方法获取结果集
		List<Map> result = EmpPhotoDao.readPhoto(param);
		if(result != null && result.size() > 0){
			for(Map map:result){
				byte[] bytes = (byte[])map.get("photo");
				if(bytes != null){
					String sbytes = new String(bytes);
					//设置HTML响应内容类型为图片
					if(sbytes.equalsIgnoreCase("GIF")){
						response.setContentType("image/gif");
					}else{
						response.setContentType("image/jpeg");
					}
					//输出图片
					output = response.getOutputStream();
					output.write(bytes,0,bytes.length);
					output.flush();
				}else{
					return;
				}
			}
		}
	}catch(Exception e) {
		e.printStackTrace();
	}
	finally{
		try{
			if(output !=null){
				//关闭流
				output.close();
				out.clear();
				out = pageContext.pushBody();
			}
		}catch (Exception e) {
			e.printStackTrace();
		}	
	}
%>
jsp显示图片代码:

<!-- src为上面jsp的路径-->

<img src="EFMPX/HR/EG/imageDownload.jsp?empId=${emp.empId}" width="107" height="155" />




   

你可能感兴趣的:(java 上传图片与图片读取)