zoukankan      html  css  js  c++  java
  • Struts2学习(四)利用ajax异步上传

    上一篇说到怎样在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='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>
    

    页面效果例如以下:
    这里写图片描写叙述
    这里写图片描写叙述

  • 相关阅读:
    进程与线程
    the art of seo(chapter seven)
    the art of seo(chapter six)
    the art of seo(chapter five)
    the art of seo(chapter four)
    the art of seo(chapter three)
    the art of seo(chapter two)
    the art of seo(chapter one)
    Sentinel Cluster流程分析
    Sentinel Core流程分析
  • 原文地址:https://www.cnblogs.com/brucemengbm/p/7080982.html
Copyright © 2011-2022 走看看