Web前端之struts2框架基于uploadify上传

晒友阁与您分享 Web前端
 最近在一个上传下载的小功能,为了更加美观,也为了练习一下,我是用了uploadify的jquery插件开发上传功能,简单的struts2下载。下面来介绍一下。
上传功能:
       上传功能,它主要包括三个层次(这里不包括数据库的链接等问题):jsp页面;struts配置文件;action层java类。
       页面上,首先要做的当然是在页面里面引入uploadify的插件。具体做法就是在<body></body>之间添加uploadify控件标签。标签内容为 <  input  type  = “file”  name  = “uploadify”  id  = “uploadify” >这里简单说明一下,type=“file”是不可以改的,这里说明标签的类型为文件类型;name和id是可以改的,且这两个属性可以不一样,但是,最好是一样的,方便选择。
      如果你想要控制上传的开始和取消,还要在这个标签下面再添加两个标签
       < a  href = “javascript:$(‘#uploadify’).uploadify(‘upload’,'*’)”  > 开始上传 </  a >  
    < a  href = “javascript:$(‘#uploadify’).uploadify(‘cancel’, ‘*’)”  > 取消所有上传 </ a  >
       这里的$(‘#uploadify’)是jquery选择器,其中uploadify是根据前面定义的id来选择的。
      到这里,标签就说完了,但是,还要调用uploadify插件。在</head>的前面添加
      < script >
      $(  function () {
           
              // 上传文件插件
            $(  “#uploadify” ).uploadify({
                          ‘fileSizeLimit’  :  ’10MB’  , // 上传限制
                          ‘buttonClass’      :  ‘ui-button’  , // 按钮样式 
                 ‘swf’                :  ‘uploadify/uploadify.swf’ , // uploadify的flash
                 ‘uploader’       :  ‘resource_ajaxadd.action’  , // struts的action方法
                 ‘cancelImg’          :  ‘uploadify/uploadify-cancel.png’  , // 取消按钮图片
                 ‘folder’             :  ‘UploadFile’ ,  // 上传的文件夹
                 ‘auto’               :   false , // 是否自动上传
                 ‘buttonText’   :  ‘选择文件’  , // 按钮文字
                 ‘fileObjName’  :  ‘uploadify’  , // 文件对象名称
              
                          ‘removeCompleted’ :  false  , // 完成后是否取消文件名 
                          // 上传成功后的方法
                          ‘onUploadSuccess’  :  function  (file, data, response) {
                                                      $( “#rsaddress”  ).val(data);
                                                  }
            });
      });
        </ script >
     小小说明一下auto这个设置,其实就是你点完选择的文件,是不是当时就传,因为咱们写了“开始上传”这个标签,所以这里就选择false了。同样,一开始的“#uploadify”也是根据标签里的id那个名字来写的。其他的先看注释,因为跟后面有很多联系,所以这里先不解释。
     还有你要引入uploadify的js和css,可以在前面那一段后面接着写,下面,要注意的是地址,如果是jsp文件,引用的路径就是WebRoot文件夹下开始写,如果是html就要考虑本文件的地址,怎么说呢,就是可能有“..”这种问题。
      <  script   src  =  “uploadify/jquery.uploadify-3.1.js”  ></ script  >
      <  link   rel  =  “stylesheet”   href  =  “uploadify/uploadify.css”  >
     好了,到这里页面页面部分就算完成了。
Struts2配置文件
     因为我是ssh配置,所以会和单独的struts2的配置有些不同。
      < action  name = “resource_*”  class = “resourceAction”  method = “{1}”  >
    </ action >
      这里我用到了通配符“*”。来简化配置文件,还记得页面里的最后一步吗,咱们有一个‘uploader’,咱们在冒号后写的‘resource_ajaxadd.action’在这里就有用了。上面action里的name属性是“resource_*”其中“*”会自动匹配“ajaxadd”(.action就是强调一下这是个action,struts里就这么要求),于是,method=“{1}”里的{1}就是第一个“*”里的内容,即“ajaxadd”。
     到这里,struts2这一部分就完成了。
Action层
     最后,来说说最让人头痛的action层。先贴代码
            private  String[]  uploadifyFileName  ;  // 接收文件的题目
       private  String[]  uploadifyContentType  ;  // 接收前台文件类型
       private  File[]  uploadify  ;  // 接收前台文件
             private  final  String  path  =  “D:/UploadFile/”  ;// 存放位置
            public  String[] getUploadifyFileName() {
              return   uploadifyFileName  ;
      }

        public   void  setUploadifyFileName(String[] uploadifyFileName) {
              this  . uploadifyFileName  = uploadifyFileName;
      }

        public  String[] getUploadifyContentType() {
              return   uploadifyContentType  ;
      }

        public   void  setUploadifyContentType(String[] uploadifyContentType) {
              this  . uploadifyContentType  = uploadifyContentType;
      }

        public  File[] getUploadify() {
              return   uploadify  ;
      }

        public   void  setUploadify(File[] uploadify) {
              this  . uploadify  = uploadify;
      }
              /**
       * uploadify上传文件
       *
       *  @return
       *  @throws  ServletException
       *  @throws  IOException
       */
        public  String ajaxadd()  throws  ServletException, IOException {

            System.  out .println( “===========我是上传功能华丽登场的分割线===============”  );

              /** 准备工作request、response **/

            HttpServletRequest request = ServletActionContext.getRequest();
            HttpServletResponse response = ServletActionContext.getResponse();
            request.setCharacterEncoding(  “UTF-8″ );
            response.setContentType(  “text/html; charset=UTF-8″ );
            PrintWriter out = response.getWriter();
              // 新文件名要加入日期
            Date date =  null ;
            
              // 新文件名容器
            StringBuilder strBuilder =  new  StringBuilder(path);
              // 输出文件
            File outFile =  null ;
              // 输出流
            FileOutputStream outStream =  null ;
              // 输入流
            FileInputStream inStream =  null ;
              // 流量
              byte [] buffer =  new  byte [1024];
              // 流量计数器
              int  l = 0;

              // 获取多文件个数
              int  length =  uploadify  . length  ;
              // 循环保存
              for  ( int  i = 0; i < length; i++) {
                    // 根据日期构造新文件名,防止命名冲突
                  date =  new  Date();
                  DateFormat df =  new  SimpleDateFormat( “yyyyMMddHHmmss”  );
                  String today = df.format(date);
                    // 拼接新文件名字符串
                  strBuilder.append(  uploadifyFileName [i]);
                    int  k = strBuilder.lastIndexOf( “.”  );
                  System.  out .println( “============”  + k);
                  strBuilder.insert(k, today);
                  System.  out .println(strBuilder.toString());

                    //存储在tomcat的项目里
//                outFile = new File(ServletActionContext.getServletContext()
//                            .getRealPath(strBuilder.toString()));
                    //存储在磁盘固定位置
                  outFile =  new  File(strBuilder.toString());
                  outStream =  new  FileOutputStream(outFile);
                  inStream =  new  FileInputStream( uploadify  [0]);
                    while  ((l = inStream.read(buffer)) > 0) {
                        outStream.write(buffer, 0, l);
                  }
                  l = 0;
                  outStream.flush();
                  out.print(strBuilder.toString());
            }
            outStream.close();
            inStream.close();

            out.flush();
            out.close();
              return  null  ;

      }

    从头开始说,第一,前三个变量必须要写,get、set方法必须生成,因为这是struts2要求的,没商量的。第二,前三个变量的名字是有讲究的“uploadify”是你的标签id名字后面加上“FileName”、“ContentType”和什么也不加。说的可能不明白,举个例子吧,如果你前面的标签id是“a”,那么这三个变量名字就是“aFileName”、“aContentType”和“a”,这次觉得说明白了。第三,我用的数组定义这三个变量,为的是进行多文件上传,如果单一文件上传就不用了。第四,第四个变量我用的是存放的位置,这里我存在了一个独立的位置,没有存在项目里,存在了“D:/UploadFile/”这个位置,写成静态变量,不用写set、get方法。
     然后最重要的ajaxadd方法,这就是struts2配置文件的method里面的那个对应的名字。
      HttpServletRequest request = ServletActionContext. getRequest();
            HttpServletResponse response = ServletActionContext.getResponse();
            request.setCharacterEncoding(  “UTF-8″ );
            response.setContentType(  “text/html; charset=UTF-8″ );
            PrintWriter out = response.getWriter();
     这一部分必须要写,作用为获取request和response还有就是防止乱码,创建输出流。剩下的看注释吧。不用返回值的。
     好了,到此为止一切大功告成!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值