####備註:這裏不詳細講解Struts2的文件上傳知識點,想了解請點擊我另外一篇文章
http://blog.csdn.net/qq_25281057/article/details/52333677
###這裏我引用了兩個js文件,一個Jquery和一個form表單插件
<script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery-1.8.2.js"></script>
<script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery-form.js"></script>
###因爲用到Ajax時候一般要解析json,所以要另外加幾個和json解析相關的jar包,我直接把這個工程所以到jar包截圖出來吧。
###jsp的前端主要頁面代碼
<hr/>
<div id="main">
<input id="file" type="file" name="uploadImage"/>
</div>
<!-- 顯示百分比 -->
<span id="percent"></span>
<span class="bar"></span>
<!-- 顯示圖片名字 -->
<div id="filename"> </div>
<!-- 顯示圖片 -->
<div id="showing" > </div>
###Jquery代碼
<script type="text/javascript">
<!--
$(function()
{
var $percent=$("#percent");//獲取進度百分比
var $bar=$(".bar");//進度條
var $showing=$("#showing");//將要顯示的圖片div
var $filename=$("#filename");//上傳文件名
var $file=$("#file");//上傳的文件
//動態添加form,利用wrap函數
$("#main").wrap("<form id='myform' method='post' enctype='multipart/form-data'></form>");
//當文件改變是觸發的事件
$("#file").change(function()
{
// window.alert("ok");
var $var_option={
//寫在Struts.xml中配置的對應action
url:'/Struct2Aajax/ajax3.action',
//dataTpye:'json',
//開始的上傳觸發的函數
beforeSend:function()
{
$showing.empty();//圖片顯示設置爲空
$percent.show();//顯示進度數
var $percentVal='0%';//初始化進度
},
//上傳過程中不斷觸發的函數
uploadProgress:function(event,position,total,percentComplete)
{
var $percentVal=percentComplete+'%';//percentComplete:改函數返回的進程數
$percent.html($percentVal);
$bar.width(percentComplete);//設置進度條view
},
//成功時觸發的函數
success:function(data)
{
//把成功返回的字符串轉成json數據;就是說要把字符串以json形式返回。
/*
例如這個項目的返回信息可以這樣:
{"name":"2.png","path":"images/2.png"}
*/
var $data=jQuery.parseJSON(data);
//獲取文件路徑
var $img=$data.path;
//動態添加標籤
$showing.html("<img src='"+$img+"' style='width:100px;height:100px;'/>");
$percent.html("上傳成功");
$file.html($data.name);
},
error:function()
{
$percent.html("上傳失敗");
}
};
$("#myform").ajaxSubmit($var_option);
})
})
//-->
</script>
###action主要代碼爲
private File uploadImage;//得到上傳的文件
private String uploadImageContentType;//得到文件的類型
private String uploadImageFileName;//得到文件的名稱
//用來返回json字符串的
private String res;
//下面節省了set和get方法,記得自行添加。
public String postPhoto() throws Exception {
Map<String, String> photoData=new HashMap<String, String>();
/*
* ServletActionContext.getServletContext().getRealPath("/")
* 是當前【程序】在磁盤中的位置,
* 如:D:\apache-tomcat-7.0.6\webapps\SchoolWeb
*/
//把文件保存到服務器的路徑
String realpath = ServletActionContext.getServletContext().getRealPath("/images/" );
File file = new File(realpath);
// 沒有此文件夾就創建
if (!file.exists())file.mkdirs();
try {
FileUtils.copyFile(uploadImage, new File(file, uploadImageFileName));
photoData.put("name",uploadImageFileName);
photoData.put("path","images"+"/"+uploadImageFileName);
// 將要返回的map對象進行json處理
JSONObject jo = JSONObject.fromObject(photoData);
// 調用json對象的toString方法轉換爲字符串然後賦值給result
this.res = jo.toString();
//返回字符串
HttpServletResponse response=ServletActionContext.getResponse();
response.setContentType("text/html;charset=utf-8");
PrintWriter pw=response.getWriter();
pw.write(this.res);
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
//記得這裏返回null,留意下面Struts.xml文件的怎麼配置
return null;
}
###Struts.xml文件的配置,因爲沒有頁面間的轉向,所以result標籤不用寫,同時包要繼承json-default
<package name="test" extends="json-default" namespace="/">
<action name="ajax3" class="com.struct2.action.PostPhotoAction" method="postPhoto">
</action>
</package>