通過Struts2、Ajax異步上傳圖片
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"onclick="uploadImage()" value="上傳" />
</form>
圖片預覽 <div id="showImage"></div>3、在頁面的js中寫上如下代碼:
</span><pre name="code" class="java"><span style="font-size:18px;">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></pre>$(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; } </pre></span><span style="font-size:18px;">通過以上的方式,我們就可以通過頁面無刷新,在Struts2中無需要進行頁面跳轉來進行圖片上傳!</span>