上传进度ProgressListener


如果上传大文件,那么上传进度的显示就比较重要,那么如何实现进度条的显示呢?

 显示文件上传进度,可以使用apache下的FileUpload组件,它的下载地址是:

http://commons.apache.org/fileupload/

它的UserGuidehttp://commons.apache.org/fileupload/using.html有详细的使用的例子和说明。

我的实现思路如下:

//   准备上传
   DiskFileItemFactoryfactory = new DiskFileItemFactory();
   factory.setSizeThreshold(2048);
   StringtempPath = AppConstants.ROOTPATH + "upload/tmp/";
   File fp1 =new File(tempPath);
   if(!fp1.exists())
    fp1.mkdirs();
        File tempFile = newFile(tempPath);        
   factory.setRepository(newFile(tempPath));
   ServletFileUploadupload = new ServletFileUpload(factory);
   upload.setSizeMax(1024000000);   
   ProgressListenerprogressListener = newUploadProgress();   
   request.getSession().setAttribute("progress",progressListener);   
   upload.setProgressListener(progressListener);   
   List items = upload.parseRequest(request);
   
   Stringcomment = ""; //存储评论
   Iterator iter= items.iterator();
   while(iter.hasNext()) {
      FileItem item = (FileItem) iter.next();
      if (item.isFormField()) {
       String name = item.getFieldName();
          String value = item.getString();
       
      if(name.equals("pid"))
      {
           pid = value;
      }
      else
         comment = value;
         
      } else {
          String fileName = item.getName();
          if(fileName == null || fileName.equals(""))
           continue;
          fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
          String ext = fileName.substring(fileName.lastIndexOf("."));
     ext=ext.toLowerCase();    
          long curTime = System.currentTimeMillis();
     Randomrandom = new Random(100000000);
     Stringfilename = String.valueOf(curTime) + "_"
       +random.nextInt(100000000) + ext;
     StringfilePath = AppConstants.ROOTPATH +"/uploadfile/"+loguser.getId()+"/files/"+pid+"/";
     Stringpath = "/uploadfile/"+loguser.getId()+"/files/"+pid+"/";
     Filefp = new File(filePath);
     if(!fp.exists())
      fp.mkdirs();
          File uploadedFile = new File(fp,filename);          
          item.write(uploadedFile);
          
如上源代码,upload.setSizeMax(1024000000); 可以设置文件上传最大支持的大小, factory.setRepository(newFile(tempPath));设置这个可以是上传大文件的时候,不是把上传的所有数据一直存入内存,而是当达到factory.setSizeThreshold(2048);所设置的文件大小后,就存入临时文件,利用这个特性可以使上传大文件的时候不会占用大量内存,可以提供用户的并发使用量。

upload.setProgressListener(progressListener); 这是设置的一个监听器,就是通过它来获取已经上传的文件的大小。

我的progressListner定义如下:

public class UploadProgress implements ProgressListener {

 private double upRate = 0.0;
 private double percent = 0.0;
 private long useTime = 0;
 private long upSize = 0;
 private long allSize = 0;
 private int item;
 
 private long beginT =System.currentTimeMillis();
 private long curT =System.currentTimeMillis();
 
 public void update(long pBytesRead, longpContentLength, int pItems) {
  
  curT =System.currentTimeMillis();    
       item = pItems;
       allSize = pContentLength;  //byte
       upSize = pBytesRead;  //byte
       useTime = curT-beginT;  //ms
       if(useTime != 0)
        upRate =pBytesRead/useTime;   //byte/ms
       else
        upRate =0.0;
       if(pContentLength == 0)
       return;
       percent =(double)pBytesRead/(double)pContentLength; //百分比
       
       
    }

 public long getAllSize() {
  return allSize;
 }

 public void setAllSize(long allSize) {
  this.allSize = allSize;
 }

 public long getBeginT() {
  return beginT;
 }

 public void setBeginT(long beginT) {
  this.beginT = beginT;
 }

 public long getCurT() {
  return curT;
 }

 public void setCurT(long curT) {
  this.curT = curT;
 }

 public int getItem() {
  return item;
 }

 public void setItem(int item) {
  this.item = item;
 }

 public double getPercent() {
  return percent;
 }

 public void setPercent(double percent) {
  this.percent = percent;
 }

 public double getUpRate() {
  return upRate;
 }

 public void setUpRate(double upRate) {
  this.upRate = upRate;
 }

 public long getUpSize() {
  return upSize;
 }

 public void setUpSize(long upSize) {
  this.upSize = upSize;
 }

 public long getUseTime() {
  return useTime;
 }

 public void setUseTime(long useTime) {
  this.useTime = useTime;
 }

}

这个监听类要继承ProgressListener 并实现update函数。

而如何实现进度的显示呢,可以通过在页面上用javascript写一个定时器,setInterval("showRequest();",1000);通过这个定时器,不断去请求后台,获取进度,进行显示,而获取进度处理函数如何获取文件上传的进度呢,可以通过request.getSession().setAttribute("progress",progressListener); 把监听类存入session,然后在获取进度的action中获取上传的进度。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Spring框架本身没有提供文件上传下载进度设置的功能,但是可以通过一些第三方库和技术来实现。 1. 文件上传进度设置 可以使用Apache Commons FileUpload库来实现文件上传进度设置。该库提供了一个ProgressListener接口,可以在上传文件时监测上传进度,并在进度发生变化时触发回调函数。 使用方法如下: ``` public class CustomProgressListener implements ProgressListener { private long bytesRead = 0; private long contentLength = 0; private int items = 0; public void update(long aBytesRead, long aContentLength, int anItem) { bytesRead = aBytesRead; contentLength = aContentLength; items = anItem; //打印上传进度 System.out.println("File upload progress: " + bytesRead + "/" + contentLength + " bytes, " + items + " items."); } } ``` 在Controller中使用该ProgressListener: ``` @RequestMapping(value="/upload", method=RequestMethod.POST) public String upload(@RequestParam("file") MultipartFile file, Model model) throws IOException { //创建文件上传对象 ServletFileUpload upload = new ServletFileUpload(); //设置进度监听器 upload.setProgressListener(new CustomProgressListener()); //上传文件 FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); //处理上传的文件 } //返回结果 return "success"; } ``` 2. 文件下载进度设置 可以使用Servlet的OutputStream和InputStream来实现文件下载进度设置。在向客户端输出文件内容时,可以读取文件内容的同时计算已经输出的字节数,并通过响应头中的Content-Length字段告知客户端文件总大小,从而计算出已下载的进度。 使用方法如下: ``` @RequestMapping(value="/download", method=RequestMethod.GET) public void download(@RequestParam("fileName") String fileName, HttpServletResponse response) throws IOException { //设置响应头 response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); //读取文件 FileInputStream fis = new FileInputStream(new File(fileName)); //设置缓冲区大小 byte[] buffer = new byte[1024]; int len = 0; long downloaded = 0; long fileLength = fis.available(); //设置响应头中的Content-Length字段 response.setHeader("Content-Length", String.valueOf(fileLength)); //向客户端输出文件内容 OutputStream os = response.getOutputStream(); while ((len = fis.read(buffer)) > 0) { os.write(buffer, 0, len); downloaded += len; //打印下载进度 System.out.println("File download progress: " + downloaded + "/" + fileLength + " bytes."); } os.flush(); os.close(); fis.close(); } ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值