框架
struts2 + Hibernate3
Jsp 页面
<div id="pic_botton"><a href="#" class="botton_05" onClick="showAddDialog();">上传新图片</a></div>
Javascript 方法:
/**
* 打开上传图片对话框
*/
function showAddDialog(){
var strWidth = "600";
var strHeight = "300";
//窗口参数
var strWinowStyle = "status:yes ; resizable:yes; ; menu:no ; dialogWidth:" + strWidth + "px ; dialogHeight:" + strHeight + "px";
//业务参数
var userId = '<s:property value="userId"/>';
var adminFlg = '<s:property value="adminFlg"/>';
var dataId = '<s:property value="dataId"/>';
var fileType = '<s:property value="fileType"/>';
var fileTypeFlyTest = '<s:property value="fileTypeFlyTest"/>';
var coptId = '<s:property value="coptId"/>';
var regUrl = encodeURI("<%=request.getContextPath()%>/initAddPicture.action?coptId="+coptId+"&userId="+userId+"&dataId="+dataId+"&fileType="+fileType+"&fileTypeFlyTest="+fileTypeFlyTest+"&random="+Math.random());
windowFlag = window.showModalDialog(regUrl, window,strWinowStyle);
if(windowFlag == "success"){
"<%=request.getContextPath()%>/pictureContent.action?random=1"+Math.random();
location.reload();
}
}
转到相应的Action
<!-- 新增图片页面 -->
<action name="initAddPicture" class="com.pera.bsdb.action.BsdbMainPictureAction" method="initAddPicture">
<result name="success">/page/coptpicture/addPicture.jsp</result>
</action>
com.pera.bsdb.action.BsdbMainPictureAction 类的initAddPicture方法没有任何动作只是返回视图页面,实现上传页面的跳转。
public String initAddPicture(){
return SUCCESS;
}
/page/coptpicture/addPicture.jsp的源码如下:
<%= "<!-- "+request.getRequestURI()+" -->" %><%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>资料文件上传</title>
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="Cache-Control" content="no-cache,must-revalidate" />
<meta http-equiv="Expires" CONTENT="0" />
<base target="_self"/>
<link href="style/css1.css" rel="stylesheet" type="text/css" />
<link href="style/div1.css" rel="stylesheet" type="text/css" />
<script language="javascript" src="js/common.js" type="text/javascript"></script>
<script language="javascript">
function doSubmit(){
if ("" == trim(document.forms[0].uploadFile.value)){
alert("请选择要上传的文件!");
document.forms[0].uploadFile.focus();
return false;
}
if (window.confirm("确定要上传该文件吗?")){
document.forms[0].btnSubmit.disabled=true;
document.forms[0].btnCancel.disabled=true;
document.forms[0].action = "<%=request.getContextPath()%>/execAddPicture.action?coptId=<s:property value='coptId'/>";
document.forms[0].submit();
}
}
function closeWindow(){
window.returnValue = "success";
window.close();
}
/**
* 页面初始化处理
*/
function initPage(){
var pageInfo = '<s:property value="pageInfo"/>';
if ( "" != pageInfo ){
alert(pageInfo);
}
var operateFlg = '<s:property value="operateFlg" />';
//alert(operateFlg);
if(operateFlg == "success"){
closeWindow();
}
}
</script>
</head>
<body onLoad="initPage()">
<form method="post" enctype="multipart/form-data">
<s:hidden name="userId"/>
<s:hidden name="adminFlg"/>
<s:hidden name="dataId"/>
<s:hidden name="fileType"/>
<s:hidden name="fileTypeFlyTest"/>
<div id="main_03_guding3">
<table border="0" cellspacing="1" cellpadding="2" class="fu_list" bgcolor="#d0d7e5" width="100%" align="left" height="98%">
<thead>
<tr class="tab_table_content">
<td colspan="10">机型图上传</td>
</tr>
</thead>
<tbody class="senfe">
<tr class="tab_table_content_sub1">
<td height="28" align="right">文件:</td>
<td><input type="file" name="uploadFile" onkeydown="JavaScript:return false;" style="width:420px"/></td>
</tr>
</tbody>
<tfoot>
<tr bgcolor="#FFFFFF" class="tfoot_button">
<td colspan="10" align="center">
<input class="anniu2with" type="button" name="btnSubmit" value="上传" onClick="doSubmit();">
<input class="anniu2with" type="button" name="btnCancel" value="取消" onClick="window.close();">
</td>
</tr>
</tfoot>
</table>
</div>
</form>
</body>
</html>
由以上页面可看出,上传页面的流程:点击 “上传“按钮 执行js方法 ” doSubmit()“
在此方法内 判断非空后 提交到后台的action“execAddPicture“处理上传业务,它的action配置为:
<!-- 新增图片 -->
<action name="execAddPicture" class="com.pera.bsdb.action.BsdbMainPictureAction" method="addPicture">
<result name="success">/page/coptpicture/addPicture.jsp</result>
<result name="input">/page/coptpicture/addPicture.jsp</result>
</action>
com.pera.bsdb.action.BsdbMainPictureAction 类的addPicture方法代码如下:
上传文件的主方法:
/**
* 上传新图片
* @return
*/
public String addPicture(){
try {
if (uploadFile.size() >= 1) {
//验证图片格式
if(!this.verifyPictureType()){
this.setPageInfo("请上传jpg格式的图片!");
return INPUT;
}
//验证图片大小
if(!this.verifyPictureSize()){
this.setPageInfo("上传图片不能大于4M!");
return INPUT;
}
String fileName = this.uploadFileFileName.get(0);
File file=this.uploadFile.get(0);
byte[] img = null;
if(file!=null){
FileInputStream fis=new FileInputStream (file);
if(fis!=null){
int len=fis.available();
img=new byte[len];
fis.read(img);
}
fis.close();
}
Integer fileSize = img.length;
Blob fileContent = Hibernate.createBlob(img);
String mainTable = Constant.MIANTABLE;
FileInf fileInf = new FileInf( fileName, fileSize, fileContent,
coptId, mainTable);
//保存前先删除
fileInfService.deleteByMainIdAndMainTable(coptId, Constant.MIANTABLE);
//保存机型图
fileInfService.save(fileInf);
}
} catch (Exception e) {
this.setPageInfo("上传失败!");
return INPUT;
}
this.setOperateFlg("success");
return SUCCESS;
}
主方法中验证文件类型的方法:
//验证文件类型
public boolean verifyPictureType(){
String[] fileName = this.uploadFileFileName.get(0).split("\\.");
if(fileName == null || fileName.length <1){
return false;
}
String type = fileName[fileName.length -1];
for(int i=0;i<Constant.PICTURETYPE.length;i++){
if(type.equals(Constant.PICTURETYPE[i])){
return true;
}
}
return false;
}
主方法中验证图片大小的方法:
//验证文件大小
public boolean verifyPictureSize() throws IOException{
//如果上传文件的大小大于规定大小
File file=this.uploadFile.get(0);
byte[] img = null;
if(file!=null){
FileInputStream fis = null;
try {
fis = new FileInputStream (file);//实例化输入流
if(fis!=null){
int len=fis.available();
img=new byte[len];
fis.read(img);
}
} catch (Exception e) {
throw new RuntimeException(e);
}finally{
fis.close();
}
}
if(!img.equals(null)
&&img.length
>Constant.PICTURESIZE){
return false;
}
return true;
}
主方法执行结束后图片已保存到数据库,返回上传的主页面(非上传弹出窗页面),查看上传的图片。
<div id="pic_main"><img src="<%=request.getContextPath()%>/getImg.action?coptId=<s:property value='coptId'/>" width="100%" height="100%"></div>
getImg action 的配置:
<!-- 获取图片 -->
<action name="getImg" class="com.pera.bsdb.action.BsdbMainPictureAction" method="getImg">
</action>
com.pera.bsdb.action.BsdbMainPictureAction 类的 显示图片的主方法getImg:
public ModelAndView getImg(){
List fileList = this.fileInfService.findByMainIdAddMainTable(coptId, Constant.MIANTABLE);
if(fileList == null || fileList.size() < 1){
this.noimage();
}else {
FileInf fileInf = (FileInf)fileList.get(0);
Blob fileContent = fileInf.getFileContent();
Integer fileSize = fileInf.getFileSize();
byte[] img = null;
try {
img = fileContent.getBytes((long)1, fileSize);
} catch (SQLException e) {
System.out.println("图片加载失败!");
}
if(img == null || img.length == 0){
this.noimage();
} else {
// 以img作为字符数组实例化一个ByteArrayInputStream
InputStream is = new java.io.ByteArrayInputStream(img);
try {
//将 byteArrayInputStream 拷贝到 outputStream
FileCopyUtils.copy(is, ServletActionContext.getResponse().getOutputStream());
} catch (IOException e) {
System.out.println("图片加载失败!");
}
}
}
return null;
}
//如果没有图片,或者图片内容为空,设置一个图片作为信息提示
public void noimage(){
String path = ServletActionContext.getRequest().getRealPath("/images/noimage.gif");
try {
FileInputStream is = new java.io.FileInputStream(new File(path));
ServletOutputStream ops = ServletActionContext.getResponse().getOutputStream();
FileCopyUtils.copy(is, ops);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e)
e.printStackTrace();
}
}
到此 上传图片的流程结束。上传图片的类型和大小 也可以放到前台的jsp页面的js函数中校验. 如:
var filePath = document.forms[0].uploadFile.value;
var fileType = filePath.split(".");
if(fileType == "" || (fileType[fileType.length -1] != 'jpg'&&fileType[fileType.length -1] != 'JPG')){
alert("请选择jpg类型的文件!");
document.forms[0].uploadFile.focus();
return false;
}