• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号
您的位置:首页 > 程序设计 >Java > struts2实现文件上传显示进度条效果

struts2实现文件上传显示进度条效果

作者:筱筱清流水 字体:[增加 减小] 来源:互联网 时间:2017-05-28

筱筱清流水 通过本文主要向大家介绍了struts2进度条,struts2 上传进度条,struts2文件上传,struts2配置文件详解,struts2文件下载等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

一. struts2读取进度原理分析(作为草稿存了好久,刚刚发布出来......)

1. 在strut2中控制文件上传信息的类是实现MultiPartRequest接口的JakartaMultiPartRequest

其实第一次看到源文件时我打了个退堂鼓,因为觉得内容太长了,不想看。冷静下来将思路理顺,将分开的各个方法还原到一个方方中中,发现还是很好理解的:

@Override
 public void parse(HttpServletRequest request, String saveDir)
   throws IOException {
  setLocale(request);
     //规定了File文件的格式(如文件名必须是xxFileName,文件类型xxContentType),并定义了File的保存路径                 DiskFileItemFactory factory = new DiskFileItemFactory(); 
  ServletFileUpload upload = new ServletFileUpload(factory);//处理文件上传的servlet
  upload.setProgressListener(new FileUploadProgressListener(request)); //为文件上传添加监听  factory.setSizeThreshold(0); //if (saveDir != null
   factory.setRepository(new File(saveDir));//临时路径
  }
  try {
   upload.setSizeMax(maxSize);
   List items = upload.parseRequest(createRequestContext(request)); //获取所有请求
   for (Object obItem : items) {
    FileItem item = (FileItem) obItem; //获取每个请求的文件
    if (LOG.isDebugEnabled()) {
     LOG.debug("Found item" + item.getFieldName());
    }
    if (item.isFormField()) { //普通表单提交
     LOG.debug("Item is a normal form field");
     List<String> values;
     if (params.get(item.getFieldName()) != null) {
      values = params.get(item.getFieldName());
     } else {
      values = new ArrayList<String>();
     }
     String charset = request.getCharacterEncoding();
     if (charset != null) {
      values.add(item.getString(charset));
     } else {
      values.add(item.getString());
     }
     params.put(item.getFieldName(), values);
    } else { //文件上传请求
     LOG.debug("Item is a file upload");
     if (item.getName() == null
       || item.getName().trim().length() <= 0) {
      LOG.debug("No file has been uploded for the filed:"
        + item.getFieldName());
      continue;
     }

     List<FileItem> values;
     if (files.get(item.getFieldName()) != null) {
      values = files.get(item.getFieldName());
     } else {
      values = new ArrayList<FileItem>();
     }
     values.add(item);
     files.put(item.getFieldName(), values);
    }
   }

  } catch (FileUploadBase.SizeLimitExceededException e) {
   System.out.println("错误1:" + e);
   if (LOG.isWarnEnabled()) {
    LOG.warn("Request exceeded size limit!", e);
   }
   String errorMessage = buildErrorMessage(e, new Object[]{e.getPermittedSize(), e.getActualSize()});
   if (!errors.contains(errorMessage)) {
    errors.add(errorMessage);
   }
  } catch (Exception e) {
   System.out.println("错误1:" + e);
   if (LOG.isWarnEnabled()) {
    LOG.warn("Unable to parse request", e);
   }
   String errorMessage = buildErrorMessage(e, new Object[]{});
   if (!errors.contains(errorMessage)) {
    errors.add(errorMessage);
   }
  }
 }

</div>

2.  文件上传监听文件FileUploadProgressListener.java

public class FileUploadProgressListener implements ProgressListener {
  private final HttpSession session;
  private final DecimalFormat format = new DecimalFormat("#00.0");

  public FileUploadProgressListener(HttpServletRequest request) {
    session = request.getSession();
    FileUploadStatus status = new FileUploadStatus();
    session.setAttribute("uploadStatus", status);
  }

  @Override
  public void update(long pBytesRead, long pContentLength, int pItems) {
    FileUploadStatus uploadStatus = (FileUploadStatus) session.getAttribute("uploadStatus");
    Double uploadRate = (double) (pBytesRead * 100 / pContentLength);
    uploadStatus.setUploadRate(Double.valueOf(format.format(uploadRate)));
    uploadStatus.setReadedBytes(pBytesRead / 1024);
    uploadStatus.setTotalBytes(pContentLength / 1024);
    uploadStatus.setCurrentItems(pItems);
  }
}

</div>

3. 添加状态文件:FileUploadStatus.java

public class FileUploadStatus {
 private Double uploadRate = 0.0;
 private Long readedBytes = 0L;
 private Long totalBytes = 0L;
 private int currentItems = 0;
 private Long uploadSpeed = 0L;
 private Long startTime = System.currentTimeMillis();
 private Long readedTimes = 0L;
 private Long totalTimes = 0L;
 // "-1" 错误 "0" 正常 "1" 完成
 private String error = "0";

 ...
  setter getter方法
 ...  
}

</div>

4. Action类(如果是多文件上传,则将File   FileName   ContentType定义成数组形式即可)

/**
 * 利用io流上传文件
 */
public class FileStreamUploadAction extends ActionSupport {
 /**
  * serialVersionUID作用: ---相当于类的身份证。 序列化时为了保持版本的兼容性,即在版本升级时反序列化仍保持对象的唯一性。
  * 有两种生成方式: 一个是默认的1L,比如:private static final long serialVersionUID = 1L;
  * 一个是根据类名、接口名、成员方法及属性等来生成一个64位的哈希字段,比如: private static final long
  * serialVersionUID = xxxxL;
  */
 private static final long serialVersionUID = 1L;
 private File image;
 private String imageFileName;
 private String imageContentType;
 private String message;
 public String uploadFile() {
  FileInputStream in = null;
  FileOutputStream out = null;
  System.out.println("文件名:" + imageFileName);
  try {
   this.setNewFileName(imageFileName);
   String realPath = ServletActionContext.getServletContext()
     .getRealPath("/file");
   File filePath = new File(realPath);
   if (!filePath.exists()) { // 如果保存的路径不存在则创建
    filePath.mkdir();
   }
   if (image == null) {
    message = "上传文件为空";
    System.out.println(message);
   } else {
    File saveFile = new File(filePath, this.getNewFileName());
    out = new FileOutputStream(saveFile);
   }
   in = new FileInputStream(image);
   byte[] byt = new byte[1024];
   int length = 0;
   while ((length = in.read(byt)) > 0) {
    out.write(byt, 0, length);
    out.flush();
   }
   message = "上传成功";
   System.out.println(message);
  } catch (FileNotFoundException e) {
   message = "找不到文件!";
   e.printStackTrace();
  } catch (IOException e) {
   message = "文件读取失败!";
   e.printStackTrace();
  } finally {
   closeStream(in, out);
  }
  return "uploadSucc";
 }
 public void closeStream(FileInputStream in, FileOutputStream out) {
  try {
   if (in != null) {
    in.close();
   }
   if (out != null) {
    out.close();
   }
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
  ...
  setter() getter()
  ...  
}

</div>

获取进度的Action

public class FileProgressAction extends ActionSupport {
  private static final long serialVersionUID = 1L;
  private FileUploadStatus uploadStatus;

  public String uploadPercent() {
    HttpSession session = ServletActionContext.getRequest().getSession();
    this.uploadStatus = (FileUploadStatus) session.getAttribute("uploadStatus");
    if (uploadStatus == null) {
      System.out.println("action is null");
      uploadStatus = new FileUploadStatus();
      uploadStatus.setCurrentItems(0);
    }
    return "getPercent";
  }

  public FileUploadStatus getUploadStatus() {
    return uploadStatus;
  }

  public void setUploadStatus(FileUploadStatus uploadStatus) {
    this.uploadStatus = uploadStatus;
  }
}

</div>

5.struts.xml中




 
分享到:QQ空间新浪微博腾讯微博微信百度贴吧QQ好友复制网址打印

您可能想查找下面的文章:

  • struts2实现文件上传显示进度条效果
  • Struts2实现文件上传时显示进度条功能
  • Struts2 文件上传进度条的实现实例代码
  • struts2实现文件上传显示进度条效果
  • Struts2实现文件上传时显示进度条功能
  • Struts2 文件上传进度条的实现实例代码

相关文章

  • 2017-05-28Java FTP上传下载删除功能实例代码
  • 2017-05-28Spring MVC学习笔记之json格式的输入和输出
  • 2017-11-12大括号{}的意义与静态代码块与构造函数的加载关系
  • 2017-07-23IntelliJIDEA平台下JNI编程(五)—本地C代码创建Java对象及引用
  • 2017-05-28spring boot整合RabbitMQ(Direct模式)
  • 2017-05-28spring之Bean的生命周期详解
  • 2017-05-28Java微信公众平台开发(5) 文本及图文消息回复的实现
  • 2017-05-28springboot + mybatis配置多数据源示例
  • 2017-05-28详解Redis 缓存 + Spring 的集成示例
  • 2017-05-28springboot集成spring cache缓存示例代码

文章分类

  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号

最近更新的内容

    • Java生产者和消费者例子_动力节点Java学院整理
    • mybatis教程之延迟加载详解
    • Java中的FileInputStream 和 FileOutputStream 介绍_动力节点Java学院整理
    • Java 操作Properties配置文件详解
    • Java语言简介(动力节点Java学院整理)
    • Java连接MongoDB进行增删改查的操作
    • Java Calendar类常用示例_动力节点Java学院整理
    • Java程序员新手老手常用的八大开发工具
    • Java date format时间格式化操作示例
    • java Socket实现简单模拟HTTP服务器

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有