前几天用commons-fileupload.jar做了个demo实现了文件或者图片的上传功能。在eclipse+struts+spring+jdbc.因为在做的过程中没想到别的好的方法,所以就直接在Action中回调了JDBC实现对数据库的操作。具体代码如下:
JSP页面:
<form name="uploadForm" action="upLoad.do?method=upLoadFile" enctype="multipart/form-data" method="post">
<table align="center">
<tr>
名称:<br>
<input type="text" name="name" size="15"><br>
请选择要上传的文件:<br>
<input type="file" name="files"><br>
<input type="submit" value="上传">
</table>
</form>
Action类的代码如下:
private static Log loger=LogFactory.getLog(UploadAction.class);
public ActionForward upLoadFile(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
String encoding =request.getCharacterEncoding();
if((encoding!=null)&&(encoding.equalsIgnoreCase("utf-8")));
{
response.setContentType("text/html; charset=gb2312");
}
UploadActionForm upForm=(UploadActionForm)form;
FormFile file=upForm.getFiles();
final String ss=upForm.getName().toString();
final InputStream is=(InputStream)file.getInputStream();
JdbcTemplate jt=(JdbcTemplate)beenFactory().getBean("jdbcDAO");//此处使用了spring封装好的jdbc Template
jt.execute("insert into upfiles(name,files) values(?,?)", new PreparedStatementCallback()
{
public Object doInPreparedStatement(PreparedStatement arg0) throws SQLException, DataAccessException
{
try
{
arg0.setString(1, ss);
arg0.setBinaryStream(2,is, is.available());
arg0.execute();
} catch (IOException e)
{
e.printStackTrace();
}
return null;
}
});
return mapping.findForward("success");
}
代码写的不全,希望对大家有帮助。