Struts2學習(四)利用ajax非同步上傳

來源:互聯網
上載者:User

標籤:fileutil   csdn   last   上傳下載   erro   str   als   war   http   

上一篇說到怎樣在struts2中進行上傳下載。我們使用了struts的標籤通過表單提交的方式,但大家知道表單提交會造成頁面總體的重新整理,這樣的方式很不友好,那我們今天就來說說怎樣結合ajax方式進行非同步上傳。

此例中須要的檔案能夠點擊這裡下載:struts2非同步所需檔案
檔案說明:
ajaxfileupload.js : jquery不支援上傳,所以使用這個ajax外掛程式,和 jquery 中的ajax使用方法差點兒相同,從以下代碼能夠看到。


json2.js : 對ajax中的回調參數進行json封裝,以此獲得參數值。由於struts2返回的json中有網頁標籤就像這樣:

,所以我們text方式返回,再通過此外掛程式拿到參數
struts2-json-plugin-2.3.15.1 : 使用json,須要加入這個jar包

代碼例如以下:
struts.xml

<?

xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"><struts><constant name="struts.devMode" value="true" /> <!-- 開發模式 --> <package name="up" extends="json-default"> <default-action-ref name="index"></default-action-ref> <action name="index"> <result>/index.jsp</result> </action> <action name="upload" class="com.etoak.action.UploadAction"> <result name="success" type="json"> <param name="contentType">text/plain</param> </result> </action> <action name="delFile" class="com.etoak.action.DelFileAction"> <result type="json"></result> </action> </package></struts>

UploadAction:
注意:我們使用struts中json方式返回後。全部寫了get方法的屬性都會被封裝到json中。返回到前台,所以不須要返回的屬效能夠把get方法凝視掉。

package com.etoak.action;import java.io.File;import java.util.List;import org.apache.commons.io.FileUtils;import org.apache.struts2.ServletActionContext;import org.omg.CORBA.PUBLIC_MEMBER;import com.etoak.util.UUIDGenerator;import com.opensymphony.xwork2.ActionSupport;public class UploadAction extends ActionSupport {    private File myfile;    private String myfileFileName;    // 又一次命名後的檔案全名    private String newFileName;    /*     * public File getMyFile() { return myFile; }     */     public void setMyfile(File myfile) {        this.myfile = myfile;    }    /*     * public String getMyfileFileName() { return myfileFileName; }     */    public void setMyfileFileName(String myfileFileName) {        this.myfileFileName = myfileFileName;    }    public String getNewFileName() {        return newFileName;    }    /*     * public void setNewFileName(String newFileName) { this.newFileName =     * newFileName; }     */    @Override    public String execute() throws Exception {        newFileName = new UUIDGenerator().generate()                + myfileFileName.substring(myfileFileName.lastIndexOf("."));        String path = ServletActionContext.getServletContext().getRealPath(                "/image")                + "/" + newFileName;        // newFileName內建getter方法,所以會加入到json中。返回前台        File destFile = new File(path);        // System.out.println(path);        FileUtils.copyFile(myfile, destFile);        return this.SUCCESS;    }}

DelFileAction:

package com.etoak.action;import java.io.File;import java.util.List;import org.apache.commons.io.FileUtils;import org.apache.struts2.ServletActionContext;import org.omg.CORBA.PUBLIC_MEMBER;import com.etoak.util.UUIDGenerator;import com.opensymphony.xwork2.ActionSupport;public class UploadAction extends ActionSupport {    private File myfile;    private String myfileFileName;    // 又一次命名後的檔案全名    private String newFileName;    /*     * public File getMyFile() { return myFile; }     */     public void setMyfile(File myfile) {        this.myfile = myfile;    }    /*     * public String getMyfileFileName() { return myfileFileName; }     */    public void setMyfileFileName(String myfileFileName) {        this.myfileFileName = myfileFileName;    }    public String getNewFileName() {        return newFileName;    }    /*     * public void setNewFileName(String newFileName) { this.newFileName =     * newFileName; }     */    @Override    public String execute() throws Exception {        newFileName = new UUIDGenerator().generate()                + myfileFileName.substring(myfileFileName.lastIndexOf("."));        String path = ServletActionContext.getServletContext().getRealPath(                "/image")                + "/" + newFileName;        // newFileName內建getter方法。所以會加入到json中,返回前台        File destFile = new File(path);        // System.out.println(path);        FileUtils.copyFile(myfile, destFile);        return this.SUCCESS;    }}

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <title>jquery非同步上傳</title>  </head>  <body>    <input type="file" name="myfile" id="myfile" />    <input type="button" value="上傳" id="upload" />    <div id="files" ></div>    <script type="text/javascript" src="script/jquery-1.10.2.js"></script>    <script type="text/javascript" src="script/json2.js"></script>    <script type="text/javascript" src="script/ajaxfileupload.js"></script><!-- jquery不支援上傳 -->        <script type="text/javascript">            $(document).ready(function(){                //上傳檔案。點擊上傳後                $("#upload").click(function(){                    var $myfile = $("#myfile").val();                    //檢查使用者是否上傳了檔案                    if($myfile!=""){                        //開始調用ajax非同步請求                        //此方法由ajaxfileupload.js提供                        $.ajaxFileUpload({                            url:"upload.action",                            type:"post",                            //提交上傳檔案的控制項                            fileElementId:"myfile",                            //是否支援跨域傳輸                            //預設不支援                            secureuri:false,                            //由於不能直接解析json,所以必須依照字串                            dataType:"text",                            success:function(data){                                alert(data);                                //將json資料從標籤中取出                                var text = $(data).html();                                //轉換為js對象                                var obj = JSON.parse(text);                                //獲得檔案資訊                                var filename = obj.newFileName;                                $("#files").append("<img name=‘"+filename+"‘ src=‘image/"+filename+"‘ style=‘width:200px;height:100px‘ />");                                //解除img元素上全部綁定的事件                                $("img").unbind();                                $("img").click(function(){                                    //拿取圖片name屬性                                    var fn = $(this).attr("name");                                    if(confirm("確定刪除?")){                                        $.ajax({                                            url:"delFile.action",                                            type:"post",                                            data:"filename="+fn,                                            dataType:"json",                                            success:function(data){                                                if(data.flag){                                                    alert("刪除成功");                                                    //拿到32位隨機碼                                                    var uuid = fn.substring(0,fn.indexOf("."));                                                    //拿取img元素name屬性開頭符合uuid的元素                                                    $("img[name^="+uuid+"]").remove();                                                }                                            }                                        });                                    }                                });                            },                            error:function(err){                                alert(err.status);                            }                        });                     }                               });            });        </script>  </body></html>

頁面效果例如以下:

Struts2學習(四)利用ajax非同步上傳

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.