1. 程式人生 > >Struts2+Ajax+Jquery的無重新整理上傳圖片

Struts2+Ajax+Jquery的無重新整理上傳圖片

####備註:這裡不詳細講解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>
###效果圖