commons-fileupload 文件上传进度条

来源:互联网 发布:视频后期特效软件 编辑:程序博客网 时间:2024/06/05 05:17

一、实现org.apache.commons.fileupload.ProgressListener接口

import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.ProgressListener;
import org.springframework.stereotype.Component;
import com.chinalife.cip.web.multipart.model.Progress;
@Component
public class FileUploadProgressListener implements ProgressListener {
    private HttpSession session;
 
    public void setSession(HttpSession session){
        this.session=session;
        Progress status = new Progress();
        session.setAttribute("status", status);
    }
 
   
    public void update(long pBytesRead, long pContentLength, int pItems) {
        Progress status = (Progress) session.getAttribute("status");
        status.setpBytesRead(pBytesRead);
        status.setpContentLength(pContentLength);
        status.setpItems(pItems);
    }
 
}

 

二、扩展org.springframework.web.multipart.commons.CommonsMultipartResolver类,重写public MultipartParsingResult parseRequest(HttpServletRequest request) throws MultipartException方法

import java.util.List;
 
import javax.servlet.http.HttpServletRequest;
 
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
 
import com.chinalife.cip.web.multipart.listener.FileUploadProgressListener;
 
public class CustomMultipartResolver extends CommonsMultipartResolver {
    @Autowired
    private FileUploadProgressListener progressListener;
    
    public void setFileUploadProgressListener(FileUploadProgressListener progressListener){
        this.progressListener=progressListener;
    }
    
    @Override
    @SuppressWarnings("unchecked")
    public MultipartParsingResult parseRequest(HttpServletRequest request)
            throws MultipartException {
        String encoding = determineEncoding(request);
        FileUpload fileUpload = prepareFileUpload(encoding);
        progressListener.setSession(request.getSession());
        fileUpload.setProgressListener(progressListener);
        try {
            List fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);
            return parseFileItems(fileItems, encoding);
        }
        catch (FileUploadBase.SizeLimitExceededException ex) {
            throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(), ex);
        }
        catch (FileUploadException ex) {
            throw new MultipartException("Could not parse multipart servlet request", ex);
        }
    }
}

 

三、springmvc配置文件上传


   

 

四、获取文件controller编写


 @RequestMapping("/uploadFile")
 public ModelAndView uploadFile(MultipartFile file,
   HttpServletRequest request) {
  System.out.println("文件上传");
  ModelAndView mv = new ModelAndView();
  String path = request.getSession().getServletContext()
    .getRealPath("/upload");
  String fileName = file.getOriginalFilename();
  String realPath = path +"/"+fileName;
  System.out.println(realPath);
  File outFile = new File(realPath);
  try {
   file.transferTo(outFile);
  } catch (Exception e) {
   e.printStackTrace();
  }
  mv.setViewName("/upload");
  return mv;
 }

五、文件进度controller编写

 @RequestMapping("/initCreateInfo")
 public ModelAndView initCreateInfo(HttpServletRequest request) {
  ModelAndView mv = new ModelAndView();
  Progress status = (Progress) request.getSession().getAttribute("status");
  if(null!=status){
    //当前读取文件的的比特数
    long a=status.getpBytesRead();
    //文件的总大小
    long b=status.getpContentLength();
    NumberFormat nf = NumberFormat.getPercentInstance();
    nf.setMinimumFractionDigits(2);//设置保留小数位
    nf.setRoundingMode(RoundingMode.HALF_UP); //设置舍入模式
    String percent = nf.format(a*1.0/b);//上传文件的百分比
    mv.addObject("p", percent);
  }
  return mv;
 }

 

六:文件上传参数实体


public class Progress {
 // 到目前为止读取文件的比特数
 private long pBytesRead;
 // 文件总大小 pItems
 private long pContentLength;
 // 目前正在读取第几个文件
 private int pItems;
 public long getpBytesRead() {
  return pBytesRead;
 }
 public void setpBytesRead(long pBytesRead) {
  this.pBytesRead = pBytesRead;
 }
 public long getpContentLength() {
  return pContentLength;
 }
 public void setpContentLength(long pContentLength) {
  this.pContentLength = pContentLength;
 }
 public int getpItems() {
  return pItems;
 }
 public void setpItems(int pItems) {
  this.pItems = pItems;
 }
}

七:文件上传jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <title>文件上传</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page">  </head>  <body>    <form action="${pageContext.request.contextPath}/student/uploadFile.html" method="post" enctype="multipart/form-data" id="upload">        <input type="file" name="file" id="file"/>          <input type="button" value="提交" id="submit">    </form>    <div id="progress" style="width: 300px;height: 18px;border-radius:10px;border: 1px solid gray;">    <span style="color: red;position: relative;left: 126px;z-index: 999" id="percent">20%</span>    <div style="background-color: green;width: 20%;display: block;position: relative;top: -18px;height: 18px;border-radius:10px;" id="perwidth"></div>    </div>    <p id="r"></p>    <script type="text/javascript" src="${pageContext.request.contextPath}/jquery-1.11.2.js"></script>    <script type="text/javascript" src="${pageContext.request.contextPath}/ajaxfileupload.js"></script>    <script type="text/javascript">    $(function(){    var s=null;     //文件异步上传     $("#submit").click(function(){    var formParam = $("#upload").serialize();    $.ajaxFileUpload({         url: '${pageContext.request.contextPath}/student/uploadFile.html',             type: 'post',            secureuri: false, //一般设置为false            fileElementId: 'file', // 上传文件的id、name属性名            dataType: 'text', //返回值类型,一般设置为json、application/json            success: function(data, status){                  //alert("上传成功");            },            error: function(data, status, e){                 alert(e);            }    });    s=setInterval (jd, 1000);    });    //从后台获取进度    function jd(){    $.ajax({             type:'post',                 url:'${pageContext.request.contextPath}/student/initCreateInfo.json',             cache:false,             dataType:'json',             success:function(d){          var p=d.p;        $("#percent").html(p);        $("#r").html(p);        $("#perwidth").css("width",p);        if("100.00%"==p){        alert("上传成功");        clearTimeout(s);        }        },        error: function(XMLHttpRequest, textStatus, errorThrown) {        clearTimeout(s);                },                complete: function(XMLHttpRequest, textStatus) {                }    });     }    });    </script>  </body></html>


0 0