📄 java+mysql图片保存和读取.txt
字号:
java+mysql图片保存和读取
作者: 西坡居士 发布日期: 2007-11-16 9:57:13
人事信息管理系统中,需要管理用户的个人身份照片。通常这种格式的照片只有几 K 到几十 K 大小,保存在数据库中易于进行管理和维护(如果放在文件夹下容易发生误操作而引起数据被修改或丢失)。
功能设计: 给用户提供一个上传的界面,并设定上传文件的尺寸上限。用户上传的照片先统一保存在一个临时文件夹中,之后可以用 <img> 指向临时文件夹中的这个图片,让用户可以预览自己上传的照片。当所有的用户信息都收集完成后,将图片和其他信息一并提交,保存到数据库中。保存成功以后,删除临时文件夹中的图片。
实现步骤:
我使用的是从 struts 主页上下载的 struts-1.2.8-src ,其中 web/examples/ 目录下有一个 upload 的例子,稍微修改了一下就直接拿过来用了。这是一个 JSP 页面、 ActionForm 和 Action 的组合。下面分别列出各自的代码。
upload.jsp 的部分源代码:
<html:form action="/UploadSubmit" enctype="multipart/form-data">
请选择需要上传的照片 :
<html:file property="theFile"/>
<html:submit value=" 上传 "/>
</html:form>
接下来需要在 ActionForm 中声明这个属性,并设置 getter 和 setter 方法,这部分源代码如下:
public class UploadForm extends ActionForm {
protected FormFile theFile;
public FormFile getTheFile() {
return theFile;
}
public void setTheFile(FormFile theFile) {
this.theFile = theFile;
}
}
这个表单的 theFile 属性不是 String 或 boolean ,而是 org.apache.struts.upload.FormFile 。因为用户上传的是一个二进制文件,而 HTTP 协议是以文本形式传输数据的,这就需要进行转换。打个比方,一辆汽车需要从甲地送到乙地,但是两地之间只有一条索道,汽车没法开,所以就想个办法在甲地把汽车先拆了,把零件送到乙地再重新组装成一辆汽车。 FormFile 起的就是拆卸和组装的作用,只不过它把拆卸、传输和组装的过程都封装起来了,我们看到的是一辆汽车从甲地开进 FormFile ,过一会它就从乙地开出来了 J 我们要决定的只是把它停到什么地方,这就是 Action 的活了。
按照功能设计, Action 要把这部车停到一个临时文件夹下面,这部分源代码如下:
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
if (form instanceof UploadForm) {
UploadForm theForm = (UploadForm) form;
// 获取上传的数据文件
FormFile file = theForm.getTheFile();
// 获取文件名
String filename= file.getFileName();
// 设置图片文件临时存放的路径
HttpSession session = request.getSession();
String path = session.getServletContext().getRealPath("/") + "temp\\" + filename;
try {
// 读取文件中的数据,获取二进制的数据流
InputStream stream = file.getInputStream();
// 把数据写到指定路径
OutputStream bos = new FileOutputStream(path);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.close();
logger.info("The file has been written to \""
+ path + "\"");
// 设计一个标记,说明用户已经上传过照片了。
session.setAttribute("imageuploaded","true");
session.setAttribute("filename",filename);
// close the stream
stream.close();
bos.flush();
bos.close();
}catch (FileNotFoundException fnfe) {
System.out.println("上传文件没找到");
return null;
}catch (IOException ioe) {
System.out.println("上传文件IO异常");
return null;
}
//destroy the temporary file created
file.destroy();
// 转向下一个页面
return mapping.findForward("next");
}
//this shouldn't happen in this example
return null;
}
这样图片就被放在 temp 的临时文件夹下,显示的时候,只需要先检查一下标记,看看用户是否上传了照片,如果已经上传,就用一个 <img src=””>
引用这个图片。还有一个小地方需要修改,因为限定上传的是身份照片,需要限定一个尺寸上限,这个在 struts 的 upload 里面有现成的例子。
先在 struts-config.xml 中配置这个 ActionForm 和 Action :
<form-bean name="uploadForm"
type="org.apache.struts.webapp.upload.UploadForm"/>
……
<action input="/pages/hr/error.jsp"
name="uploadForm"
path="/UploadSubmit"
scope="request"
type="org.apache.struts.webapp.upload.UploadAction"
validate="true">
<forward name="next" path="/pages/hr/input.jsp"/>
</action>
……
<controller maxFileSize="2M" inputForward="true" />
在配置文件中已经看到 <action> 的 validate 属性被设置成“ true ”,这就是说表单提交之前先要对其内容进行验证,
这里我们要验证的就是 theFile 是否超出了 controller 中设定的最大尺寸 ”2M” 。这个验证是通过 ActionForm 的 validate 方法来实现的:
/**
* Check to make sure the client hasn't exceeded the maximum allowed upload size inside of this validate method.
**/
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
ActionErrors errors = null;
//has the maximum length been exceeded?
Boolean maxLengthExceeded =
(Boolean) request.getAttribute(
MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED);
if ((maxLengthExceeded != null) && (maxLengthExceeded.booleanValue())) {
errors = new ActionErrors();
errors.add(
ActionMessages.GLOBAL_MESSAGE ,
new ActionMessage("maxLengthExceeded"));
errors.add(
ActionMessages.GLOBAL_MESSAGE ,
new ActionMessage("maxLengthExplanation"));
}
return errors;
}
这里我估计有个 hook 之类的东西先截获了表单(应该和 controller 有关),对 theFile 的尺寸进行校验,然后把结果保存在 request scope 中。
Validate 方法只要检查一下这个结果就可以了,如果尺寸超标,表单就不会被提交给 Action 。
以上算是完成了第一步,从用户那里拿到照片,并保存在临时文件夹当中。接下来要做的就是把照片保存到 MySQL 数据库中,这个字段我用的是
MEDIUMBLOB ,因为 BLOB 最大长度是 216-1 字节,大约 64K ; MEDIUMBLOB 是 224-1 字节,约 16M ,足够用了。保存图片的主要代码如下:
/**
* 将用户的照片保存在数据表中,添加成功后,删除临时文件夹中的图片。
* @param id 用户的身份号,作为图片的标识码
* @param path 图片存放的路径。一般存放在一个临时文件夹中。
* @return
*/
public static void saveImage(int id, String path) throws SQLException{
String time = new java.util.Date().toString();
Connection conn = null;
PreparedStatement pstmt = null;
boolean flag = false;
// 获取连接
try {
conn = DbManager.getConnection();
logger.info(time + ":saveImage() 从 DbManager 数据库连接池获取一个连接。 ");
} catch (SQLException e) {
// 如果没有能够从 DbManager 获取连接,此次查询操作失败
logger.error(time + ": saveImage() 不能获取数据库连接,无法保存图片! ");
throw new SQLException(":saveImage() 不能获取数据库连接,无法保存图片! ");
}
// 执行查询
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -