昨天干啥了?呵呵,昨天没过来写,哈哈现在是周五了,噢对,哈哈,昨天有活干了,让我做一个上传图片,把图片报存在数据库中,然后再读出来显示,要能查 询、添加、删除。好了动手吧,以前做过一个上传图片,但是不是把图片报存在数据库中,大同小异了。把关键代码贴在这里,供以后参考。
-----------------------------上传页面---------------------------------------------------------------
<%@page contentType="text/html; charset=gb2312" %>
<%@ taglib uri="/WEB-INF/struts-html" prefix="html"%>
<html>
<head>
<title>上传图片</title>
</head>
<body>
<h2>选择图片(JPEG格式, 大小小于1M)</h2>
<br>
<html:form action="/upload.do" enctype="multipart/form-data">
<html:errors/>
<table>
<tr>
<TD><html:file property="file" size="50"></html:file></TD>
</tr>
<TR height="20" valign="top" topmargin="0">
<TD>备注:</TD>
</tr>
<tr>
<TD><html:textarea rows="3" cols="40" property="memo"></html:textarea></TD>
</TR>
<tr>
<tr height="20">
</tr>
<tr>
<TD height="22" align="center">
<html:submit> 上 传 </html: submit> <input type="button" value=" 取 消 " onclick="window.close()"/></TD>
</tr>
</table>
</html:form>
</body>
</html>
--------------------------------------action--UploadAction-----------------------------------------------------
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setCharacterEncoding("gb2312"); //如果不设置,弹出的提示框是乱码
UploadForm uploadForm = (UploadForm) form;
FormFile file = uploadForm.getFile();
String memo = uploadForm.getMemo();
String fileName = file.getFileName();
int length = file.getFileSize();
InputStream imgStream = null;
ActionMessages msgs = new ActionMessages();
//向数据库插入记录
try {
imgStream = file.getInputStream();
UserImg newUserImg = new UserImg();
newUserImg.setImg(imgStream);
newUserImg.setImgName(fileName);
newUserImg.setMemo(memo);
newUserImg.setFileSize(length);
if(UploadImageDao.getInstance().insertImg(newUserImg))
{
response.getWriter().write(
CSScript.alertAndCloseScript(MessageKey.IMAGE_UPLOAD_SUCCESS));
return null;
}
else
{
msgs.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
MessageKey.IMAGE_UPLOAD_FAILED));
saveErrors(request, msgs);
}
} catch (IOException e) {
msgs.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
MessageKey.IMAGE_UPLOAD_FAILED));
saveErrors(request, msgs);
} finally {
try {
if (imgStream != null)
imgStream.close();
} catch (Exception e) {
//do nothing here
}
}
return mapping.getInputForward();
}
--------------------------------------弹出提示框的类----------------------------------------------------------
public final class CSScript {
private static final String S_OPEN = "<script>";
private static final String S_CLOSE = "</script>";
public static String alertAndCloseScript(String alert)
{
StringBuffer sb = new StringBuffer(S_OPEN);
sb.append("alert('").append(alert).append("!');");
sb.append("window.close();");
sb.append("window.opener.document.location.reload();");
sb.append(S_CLOSE);
return sb.toString();
}
public static String errorScript(String err)
{
StringBuffer sb = new StringBuffer(S_OPEN);
sb.append("alert('").append(err).append("!');");
sb.append(S_CLOSE);
return sb.toString();
}
public static String alertScript(String alert)
{
StringBuffer sb = new StringBuffer(S_OPEN);
sb.append("alert('").append(alert).append("!');");
sb.append(S_CLOSE);
return sb.toString();
}
}
---------------------------------------插入数据库的方法-----------------------------------------------------
public boolean insertImg(UserImg userImg)
{
Session session = HibernateSessionFactory.getSession();
Transaction tran = session.beginTransaction();
try
{
Connection conn = session.connection();
PreparedStatement psta = conn.prepareStatement("insert into userImg values(?,?,?)");
psta.setString(1,userImg.getImgName());
psta.setBinaryStream(2, userImg.getImg(),userImg.getFileSize());
psta.setString(3, userImg.getMemo());
psta.execute();
tran.commit();
}
catch(Exception e)
{
e.printStackTrace();
tran.rollback();
return false;
}
finally
{
HibernateSessionFactory.closeSession();
}
return true;
}
注意,这里可以看到涌到了hibernate的session,但还是用的jdbc插入数据库,是因为hibernate对image类型的字段支持不好。
-----------------------------------------读取图片的action-getImg.do-----------------------------------------------------------
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
int id = Integer.parseInt(request.getParameter("id"));
InputStream inStream = UploadImageDao.getInstance().getImg(id);
response.setContentType("image/pjpeg");
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = inStream.read(buffer, 0, 1024)) != -1) {
baos.write(buffer, 0, bytesRead);
}
OutputStream outs = response.getOutputStream();
outs.write(baos.toByteArray());
outs.flush();
inStream.close();
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
页面中显示图片,这么写
<img width="100" height="100" src="getImg.do?id=<bean:write name="list" property="id"/>" />