java上传图片和图片读取demo详解编程语言

java上传图片和图片读取demo详解编程语言

首先是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(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实现下载功能:

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二进制数组转成图片

<html code_snippet_id="96378" snippet_file_name="blog_20131204_2_1772916" name="code" class="java">
<[email protected] 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" />
</html>

java上传图片和图片读取demo详解编程语言

转载请注明来源网站:blog.ytso.com谢谢!

原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/14729.html

(0)
上一篇 2021年7月19日
下一篇 2021年7月19日

相关推荐

发表回复

登录后才能评论