在写一个程序时我遇到了要将图片存入数据库的操作,在网上也没找见好的解决方法,最后请教了同事才解决.我想有的人可能用得到,就把它写出来.我只写一些核心的与图片操作相关的代码.
图片存入数据库及取出显示在网页上: 存入及取出显示都需要用到上传文件时的jspsmart.jar包。在页面上加入一些方法即可实现。需要注意的是:存取 数据库的时要用PreparedStatement而不能用Statement,否则的话图片是存不进去的,你去找原因可能得发 不少时间哦。
<%@ page contentType="text/html; charset=GBK" %> <%@ page java.io.*" %> <%@ page import="com.jspsmart.upload.*" %> <% SmartUpload su = new SmartUpload(); // 上传初始化 su.initialize(pageContext); // 设定上传限制 // 1.限制每个上传文件的最大长度。 // su.setMaxFileSize(10000); // 2.限制总上传数据的长度。 // su.setTotalMaxFileSize(20000); // 3.设定允许上传的文件(通过扩展名限制),仅允许doc,txt文件。 // su.setAllowedFilesList("jpg,jpeg"); // 4.设定禁止上传的文件(通过扩展名限制),禁止上传带有exe,bat,jsp,htm,html扩展名的文件和没有扩展名的文件。 // su.setDeniedFilesList("exe,bat,jsp,htm,html,,"); // 上传文件 //System.out.println("test 1"); su.upload(); //System.out.println("test 2"); byte[] fileBytes = null; for (int i = 0; i < su.getFiles().getCount(); i++) { //System.out.println("test 3"); com.jspsmart.upload.File uploadFile = su.getFiles().getFile(i); if (!uploadFile.isMissing()) { //System.out.println("test 4"); //xmlFileName = uploadFile.getFilePathName(); fileBytes = new byte[uploadFile.getSize()]; for (int j = 0; j < uploadFile.getSize(); j++) { //System.out.println("test 5"); fileBytes[j] = uploadFile.getBinaryData(j); } break; } } %>
fileBytes就是上传图片的的字节数组,得到了这个我们就能在java代码中存入数据库了。
显示图片,这里作为一个单独的jsp 页面getImage.jsp. 另一个页面info.jsp里在显示图片的地方<img src="getImage.jsp?id=1" > id根据情况要做以改变,我这只是说明问题.
<%@ page contentType="text/html; charset=GB2312" %> <%@ page import="java.io.*"%> <%@ page import="com.Info" %> <jsp:useBean id='dbex' scope='page' class='com.Dbex' type="com.Dbex" /> <jsp:useBean id='fi' scope='page' class='com.Info' /> <% String id=fi.getGbk(request.getParameter("id")); Info info= dbex.findById(id); out.clearBuffer(); response.setContentType("image/jpg"); byte[] photo=info.getPhoto();//photo为从数据库里取出的图片的字节数组 ByteArrayOutputStream imageStream=new ByteArrayOutputStream(); if(photo!=null){ imageStream.write(photo); } ServletOutputStream streamOut=response.getOutputStream(); imageStream.writeTo(streamOut); streamOut.close();
%>
我在这里只是大概说了说,有兴趣的朋友可以自己试试.
|