1、下载JS插件jquery-1.4.2.min.js和jquery.form.js
2、HTML中的form表单如下:
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>//引入插件
<script type="text/javascript" src="js/jquery.form.js"></script>
<form id="form2" method="post" enctype="multipart/form-data">
<input id="fileupload" name="fileMaterial" type="file" />
<div id="message"></div>
<input type="button" class="right-button02"οnclick="uploadImage()" value="上传" />
</form>
图片预览 <div id="showImage"></div>
3、在页面的js中写上如下代码:
function uploadImage() {
$(document).ready(
function() {
var options = {
url : "<%=path%>/material.action!ajaxGetImage.do",//跳转到相应的Action
type : "POST",//提交方式
dataType : "script",//数据类型
success : function(msg) {//调用Action后返回过来的数据
alert(msg);
if (msg.indexOf("#") > 0) {
var data = msg.split("#");
var data = msg.split("#");
$("#message").html("<font color='red'>"+data[0]+data[2]+"</font>");
$("#showImage").html("<img src='<%=webBasePath%>"+data[1]+"'/>");
} else {
$("#message").html(msg);//在相应的位置显示信息
}
}
};
$("#form2").ajaxSubmit(options);//绑定页面中form表单的id
return false;
});
}
</script>
$(document).ready()表示在直接加载
4、传到相应的Action,uploadFile.action
public class MaterialAction extends BasicAction{
private File fileMaterial;//Ajax获取图片文件,与控件type=File中的name属性一样
private String fileMaterialFileName;//Ajax获取图片文件名称,相应的name属性名称+FileName
-----------相应的get和set方法----------------
/**
* 通过Ajax获取图片信息
* @return
* @throws IOException
*/
public String ajaxGetImage() throws IOException{
HttpServletResponse response=ServletActionContext.getResponse();
response.setContentType("text/plain");
response.setCharacterEncoding("utf-8");
if(fileMaterial!=null){
String fileName=UUID.randomUUID()+"."+getFileType(fileMaterialFileName);
String savePath=ServletActionContext.getServletContext().getRealPath("cookBookImage")+"/material/"+fileName;
ImageZipUtil.zipWidthHeightImageFile(fileMaterial, new File(savePath), 40, 40, 1.0f);//压缩图片上传的公共类
String imgUrl="cookBookImage/material/"+fileName;
response.getWriter().print("图片#"+imgUrl+"#上传成功!");//把相应的地址放到前台解析,通过#符号分割
}else{
response.getWriter().print("图片上传失败!");
}
return null;
}
通过以上的方式,我们就可以通过页面无刷新,在Struts2中无需要进行页面跳转来进行图片上传!