zyUpload+struct2完成文件上传

v前言:

  最近在写自己的博客网站,算是强化一下自己对s2sh框架的理解。期间遇到了很多问题,这些问题在写之前都考虑过,感觉也就是那样吧。但正真遇到了,也挺让人难受的。就利用zyUpload这个js插件实现文件的上传, 我来谈一谈。

vzyUpload下载:

  https://github.com/hjzgg/zyUpload ,或者可以在网上,随便就可以下载到,只不过提供的网址中的zyUpload是我改过的。

vzyUpload界面效果:

vzyUpload使用需要注意的几个地方: 

   说明:zyUpload 配合Strus2实现图片或文件的上传

  (1)zyFile.js,lanrenzhijia.js,zyUpload.js设置 url : "fileUploadAction!execute", // 上传文件的路径
(2)文件的上传通过 zyFile.js中的funUploadFile函数,修改formdata.append("upload", file) file对应的name属性值,这里是"upload",保证和后台的name属性值一样!上传的代码如下:

// 上传多个文件
        funUploadFiles : function(){
            var self = this;  // 在each中this指向没个v  所以先将this保留
            // 遍历所有文件  ,在调用单个文件上传的方法
            $.each(this.uploadFile, function(k, v){
                self.funUploadFile(v);
            });
        },
        // 上传单个个文件
        funUploadFile : function(file){
            var self = this;  // 在each中this指向没个v  所以先将this保留

            var formdata = new FormData();
            formdata.append("upload", file);
            var xhr = new XMLHttpRequest();
            // 绑定上传事件
            // 进度
            xhr.upload.addEventListener("progress",     function(e){
                // 回调到外部
                self.onProgress(file, e.loaded, e.total);
            }, false);
            // 完成
            xhr.addEventListener("load", function(e){
                // 从文件中删除上传成功的文件  false是不执行onDelete回调方法
                self.funDeleteFile(file.index, false);
                // 回调到外部
                self.onSuccess(file, xhr.responseText);
                if(self.uploadFile.length==0){
                    // 回调全部完成方法
                    self.onComplete("全部完成");
                }
            }, false);
            // 错误
            xhr.addEventListener("error", function(e){
                // 回调到外部
                self.onFailure(file, xhr.responseText);
            }, false);
            xhr.open("POST", self.url, true);
            xhr.send(formdata);
        },

(3)缺陷就是只能单个文件上传!用的是FormData对象,利用ajax技术,每次上传都要请求后台。
(4)zyFile.js中的一些接口都是在zyUpload.js中实现!

     下面是zyFile.js中的一些接口

filterFile : function(files){ // 提供给外部的过滤文件格式等的接口,外部需要把过滤后的文件返回

        },
        onSelect : function(selectFile, files){      // 提供给外部获取选中的文件,供外部实现预览等功能  selectFile:当前选中的文件  allFiles:还没上传的全部文件

        },
        onDelete : function(file, files){            // 提供给外部获取删除的单个文件,供外部实现删除效果  file:当前删除的文件  files:删除之后的文件

        },
        onProgress : function(file, loaded, total){  // 提供给外部获取单个文件的上传进度,供外部实现上传进度效果

        },
        onSuccess : function(file, responseInfo){    // 提供给外部获取单个文件上传成功,供外部实现成功效果

        },
        onFailure : function(file, responseInfo){    // 提供给外部获取单个文件上传失败,供外部实现失败效果

        },
        onComplete : function(responseInfo){         // 提供给外部获取全部文件上传完成,供外部实现完成效果

        },

zyFile.js中filterFile给外部提供的函数接口在 zyUpload.js可以找到,用来进行文件的过滤!对于filterFile这个借口,实现如下(当然,你可以根据自己的需求自己来实现,我这里只是想上传图片文件而已):

this.funFilterEligibleFile = function(files){
                var arrFiles = [];  // 替换的文件数组
                for (var i = 0, file; file = files[i]; i++) {
                    if (file.size >= 51200000) {
                        alert('您这个"'+ file.name +'"文件大小过大');
                    } else {
                        // 在这里需要判断当前所有文件中
                        var fileExt = file.name.substr(file.name.lastIndexOf(".")).toLowerCase();//获得文件后缀名
                        if(fileExt==".png" || fileExt==".gif" || fileExt==".jpg" || fileExt==".jpeg")
                            arrFiles.push(file);//如果文件是图片格式,那么就放入文件的数组
                        else {
                            alert("文件仅限于 png, gif, jpeg, jpg格式 !");
                        }
                    }
                }
                return arrFiles;
            };

       filterFile: function(files) {
                 // 过滤合格的文件
                 return self.funFilterEligibleFile(files);
            },

vstruct2后台处理:

v1.structs.xml中配置文件上传解析器

<!-- struct2默认使用jakarta的Common-FileUpload的文件上传解析器 -->
  <constant name="struts.multipart.parser" value="jakarta"/>

v2.structs.xml中action的配置

 <action name="fileUploadAction" class="fileUploadAction" method="struts-default">
        <param name="savePath">/fileUpload</param>
        <result name="errors" type="redirect">/errorsMessage/fileErrorsTip.jsp</result>
        <result name="operations" type="redirect">/operationsMessage/fileOperationsTip.jsp</result>
   </action>

v3.dao层

public class PictureDao implements Serializable{
    private SessionFactory sessionFactory;

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    private Session getSession(){
        return sessionFactory.getCurrentSession();
    }

  public PictureGroup pictureJspGetOneGroup(int groupId){//得到相册的分组
        PictureGroup pictureGroup = null;
        Session session = null;
        Transaction tran = null;
        try{
            session = this.getSession();
            tran = session.beginTransaction();
            pictureGroup = (PictureGroup)session.createQuery("from PictureGroup where groupId="+groupId).list().get(0);
            tran.commit();
        } catch(Exception e) {
            System.out.println(e.toString());
            tran.rollback();
            return null;
        }
        return pictureGroup;
    }

    public String newMyPicture(MyPicture myPicture){//持久化图片信息
        Session session = null;
        Transaction tran = null;
        try{
            session = this.getSession();
            tran = session.beginTransaction();
            session.persist(myPicture);
            tran.commit();
        } catch(Exception e){
            System.out.println(e.toString());
            tran.rollback();
            return e.toString();
        }
        return null;
    }

}

v4.action部分

public class FileUploadAction extends ActionSupport{
    private PictureDao pictureDao;
    public PictureDao getPictureDao() {
        return pictureDao;
    }
    public void setPictureDao(PictureDao pictureDao) {
        this.pictureDao = pictureDao;
    }

    private List<File>    upload; // 上传的文件
    private List<String> uploadFileName; // 文件名称
    private List<String> uploadContentType; // 文件类型
    private String savePath;

    public List<File> getUpload() {
        return upload;
    }
    public void setUpload(List<File> upload) {
        this.upload = upload;
    }
    public List<String> getUploadFileName() {
        return uploadFileName;
    }
    public void setUploadFileName(List<String> uploadFileName) {
        this.uploadFileName = uploadFileName;
    }
    public List<String> getUploadContentType() {
        return uploadContentType;
    }
    public void setUploadContentType(List<String> uploadContentType) {
        this.uploadContentType = uploadContentType;
    }
    public String getSavePath() {
        return savePath;
    }
    public void setSavePath(String savePath) {
        this.savePath = savePath;
    }

    private String pictureName = null;
    private String picturePath = null;
    private String pictureGroupId = null;
    public String fileUploadSuccess(){//添加一张图片
        try{
            MyPicture myPicture = new MyPicture();
            myPicture.setPictureName(pictureName);
            myPicture.setPicturePath(picturePath);
            myPicture.setPictureBuildTime(new Timestamp(System.currentTimeMillis()));
            PictureGroup pictureGroup = pictureDao.pictureJspGetOneGroup(Integer.parseInt(pictureGroupId));//为了得到持久化的相册分组对象
            if(pictureGroup == null) throw new NullPointerException("分组为空!");
            myPicture.setGroup(pictureGroup);
            String msg = pictureDao.newMyPicture(myPicture);
            ActionContext.getContext().getSession().put("operations", "图片" + pictureName + (msg==null ? "上传成功!" : "上传失败:"+msg));
        } catch (Exception e){
            System.out.println(e.toString());
            ActionContext.getContext().getSession().put("errors", "图片" + pictureName + "添加失败: " + e.toString() + " 异常位置: FileUploadAction!fileUploadSuccess。");
            return "errors";
        }
        return "operations";
    }

    @Override
    public String  execute() throws Exception {
        try{
            // 取得需要上传的文件数组
            List<File> files = getUpload();
            HttpServletRequest request = ServletActionContext.getRequest();
            //得到 到 项目根目录的URL
            String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
            if (files != null && files.size() > 0) {
                String realPath = ServletActionContext.getServletContext().getRealPath(savePath);
                //多个文件的上传
//                for (int i = 0; i < files.size(); i++) {
//                    String fileName = System.currentTimeMillis()+getUploadContentType().get(i).replace("/", ".");
//                    picturesPath.add(url+savePath+"/"+fileName);
//                    FileOutputStream fos = new FileOutputStream(realPath + "\\" + fileName);
//                    FileInputStream fis = new FileInputStream(files.get(i));
//                    byte[] buffer = new byte[1024];
//                    int len = 0;
//                    while ((len = fis.read(buffer)) > 0) {
//                        fos.write(buffer, 0, len);
//                    }
//                    fis.close();
//                    fos.close();
//                }

                if((pictureGroupId=(String)ActionContext.getContext().getSession().get("pictureGroupId")) == null){//未选择分组
                    ActionContext.getContext().getSession().put("operations", "图片"+uploadFileName+"上传失败,分组未选择! <a target='_parent' href='../pictureAction!pictureGroupJspGetAllGroups'>选择分组</a>");
                    return "operations";
                }

                //处理单个文件的上传
                String fileName = System.currentTimeMillis()+getUploadFileName().get(0)+getUploadContentType().get(0).replace("/", ".");
                FileOutputStream fos = new FileOutputStream(realPath + "\\" + fileName);
                FileInputStream fis = new FileInputStream(files.get(0));
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = fis.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }
                fis.close();
                fos.close();
                picturePath = url+savePath+"/"+fileName;
                pictureName = getUploadFileName().get(0);
                return fileUploadSuccess();
            } else {
                ActionContext.getContext().getSession().put("errors", "得到文件数目为0! 异常位置:FileUploadAction!execute。");
            }
        } catch (Exception e){
            System.out.println(e.toString());
            ActionContext.getContext().getSession().put("errors",  "图片" + getUploadFileName().get(0) + "上传失败: " + e.toString()+"异常位置:FileUploadAction!execute。");
            return "errors";
        }
        return "errors";
    }
}

v5.说一下Action中的一些信息:

  String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath(); 得到请求项目的地址,如http://localhost:8080/myBlog;

  String fileName = System.currentTimeMillis()+getUploadFileName().get(0)+

               getUploadContentType().get(0).replace("/", "."); 生成唯一文件名称。

  String realPath = ServletActionContext.getServletContext().getRealPath(savePath);得到图片的存储地址

  picturePath = url+savePath+"/"+fileName;得到图片的src地址

v最终效果:

  1.上传后,无论是失败还是成功,都可以通过ajax从后台得到!

  2.最后从后台得到数据并展示

  好了,自己的博客网站算是差不多了,这一个多星期真是累尿了。接下来好好看看书,刷刷题,做做题,准备找工作吧。噢耶!!!

时间: 2024-08-29 04:02:31

zyUpload+struct2完成文件上传的相关文章

JAVA WEB怎么实现大文件上传(上G的文件)

问题描述 JAVAweb怎么实现上G的文件上传.好像用Struct2对大文件支持有限.比如百度云硬盘,还要邮箱的大附件上传方式.都是用什么技术实现的,activex技术,ftp方式,还是其他什么方式 解决方案 解决方案二:解决这种大文件上传不太可能用web上传的方式,只有自己开发插件或是当门客户端上传,或者用现有的ftp等.1)开发一个web插件.用于上传文件.2)开发一个FTP工具,不用web上传.3)用现有的FTP工具.下面是几款不错的插件,你可以试试:1)Jquery的uploadify插

JavaBean实现多文件上传的两种方法

上传 摘要:本文介绍了JavaBean实现多个文件上传的两种方法,分别是使用http协议和ftp协议实现.首先讲述了http协议传送多个文件的基本格式和实现上传的详细过程,之后简单介绍了使用ftpclient 类实现了ftp方式的上传,最后对这两种方法进行了比较. 关键字:JavaBean .http .ftp .ftpclient JavaBean是一种基于Java的软件组件.JSP对于在Web 应用中集成JavaBean组件提供了完善的支持.这种支持不仅能缩短开发时间(可以直接利用经测试和可

java--uploadify3.1多文件上传

使用uploadify时,建议下载uploadify3.1文档.边做边看.    这是页面端: <label style="color:#15428B;font-weight:bold;">选择文件:</label> <fieldset style="width:300px;height:33px;border:1px solid #99BBE8;text-align:left;COLOR:#000000;FONT-SIZE:12px;font-

JSP利用组件实现文件上传的全攻略

js|攻略|上传 一.首先下载jspsmartupload组件 http://dboy520.51.net/cgi-bin/newjavajia/downcount.php?id=22 (本站地址) http://www.jspsmart.com 二.将目录jspsmartupload/wib_inf/classes中的内容拷贝到网站所在的实际目录中的WEB-INF中(resin是这个目录,其他的可能是classes,具体请查阅jspsmartupload/help/setup.htm) 三.如

html5文件上传

上文介绍了如何通过ajax异步上传文件,html5对file的新接口,可以使得在页面上,对用户也有更好的体验. 页面上要做的,仅仅是添加一个html标签: [cce lang="html"] <input id="track" name="track" type="file" multiple="multiple" onchange="showInfo();" /> [/cc

Spring 文件上传功能

本篇文章,我们要来做一个Spring的文件上传功能: 1. 创建一个Maven的web工程,然后配置pom.xml文件,增加依赖: 1 2 3 4 5 <dependency>     <groupId>org.springframework.boot</groupId>     <artifactId>spring-boot-starter-web</artifactId>     <version>1.0.2.RELEASE<

django 文件上传 验证-django文件上传的格式验证问题,在线等!

问题描述 django文件上传的格式验证问题,在线等! 用django写入个文件上传的页面,需要上传文件名称和文件,且文件名只能为数字: class uploadForm(forms.Form): name = forms.IntegerField() headImg = forms.FileField() 遇到一个问题: 当上传的文件很大时,需要等文件上传完成后才会去验证文件名的格式是否为数字,如果 文件名不是纯数字上传就失败了,又得花很长时间重新上传,这显然是不合理的, django有什么方

http协议- 使用http put把本地文件上传到服务器的的时候碰到的问题

问题描述 使用http put把本地文件上传到服务器的的时候碰到的问题 各位好,我在用libcurl的接口往localhost服务器上传文件里上传文件的时候出现了下面的错误(用的机器系统是linuxmint17,搭建的服务器Apache + PHP5 + MySQL)*** We read 4257 bytes from file<!DOCTYPE HTML PUBLIC ""-//IETF//DTD HTML 2.0//EN""> 405 Method

文件上传是存在硬盘上,还是存在数据库中?

问题描述 文件上传是存在硬盘上,还是存在数据库中? 如果有比较多的文件上传,上千个文件,大小2-3MB,是存在硬盘上,还是存在数据库中? 存在硬盘上,路径保存在数据库中,是比较方便,但是存在一台server上出问题怎么办?是不是应该转换成google二进制存到数据库(MySQL)中? 解决方案 直接备份文件系统啊,这是最基本的,存到数据库很费劲的.而且你的文件还特别多.不划算了,. 解决方案二: 附件多媒体室存硬盘,其它的文字数据存数据库 解决方案三: 比较通行的办法是,将文件存在硬盘中,数据库