Home  >  Article  >  Web Front-end  >  Steps to implement fileUpload upload file with progress bar effect

Steps to implement fileUpload upload file with progress bar effect

php中世界最好的语言
php中世界最好的语言Original
2018-03-31 15:33:561474browse

This time I will bring you the steps to implement the fileUpload upload file with progress bar effect. What are the precautions to implement fileUpload upload file with progress bar effect. The following is the actual combat. Let’s take a look at the case.

During the file upload process, it would be better if we could see the progress bar. The implementation idea is that the server uses a listener to monitor the progress in real time and saves it in the session, and the client asynchronously requests the server. Get the upload progress and perform effect rendering.

Rendering:

## Server-side servlet:

public class UploadServlet extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    //取出监听器MyProgress在session中保存的进度信息
    String progress=(String) req.getSession().getAttribute("progress");
    //响应
    resp.getWriter().print(progress);
    //清除session中保存的数据
//    req.getSession().removeAttribute("progress");
  }
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    req.setCharacterEncoding("UTF-8");
    DiskFileItemFactory factory=new DiskFileItemFactory();
    ServletFileUpload upload=new ServletFileUpload(factory);
    upload.setProgressListener(new MyProgressListener(req));
    try {
      List list = upload.parseRequest(req);
      for (FileItem fileItem : list) {
        if (fileItem.isFormField()) {//普通表单
        }else{//上传文件
          String path=req.getRealPath("uploads");
          String fileName=fileItem.getName();
          File file=new File(path, fileName);
          fileItem.write(file);
          System.out.println("成功上传文件:"+fileName);
        }
      }
    } catch (Exception e) {
      System.out.println("文件上传发生错误!");
      e.printStackTrace();
    }
  }
}

Server-side listener:

public class MyProgressListener implements ProgressListener {
  private HttpSession session;
  public MyProgressListener(HttpServletRequest request){
    session = request.getSession();
  }
  @Override
  public void update(long pBytesRead, long pContentLength, int pItems) {
    //将数据进行格式化
    //已读取数据由字节转换为M
    double readM=pBytesRead/1024.0/1024.0;
    //已读取数据由字节转换为M
    double totalM=pContentLength/1024.0/1024.0;
    //已读取百分百
    double percent=readM/totalM;
    
    //格式化数据
    //已读取
    String readf=dataFormat(pBytesRead);
    //总大小
    String totalf=dataFormat(pContentLength);
    //进度百分百
    NumberFormat format=NumberFormat.getPercentInstance();
    String progress=format.format(percent);
    
    //将信息存入session
    session.setAttribute("progress", progress);
    
    //打印消息到控制台
    System.out.println("pBytesRead===>"+pBytesRead);
    System.out.println("pContentLength==>"+pContentLength);
    System.out.println("pItems===>"+pItems);
    System.out.println("readf--->"+readf);
    System.out.println("totalf--->"+totalf);
    System.out.println("progress--->"+progress);
  }
  /**
   * 格式化读取数据的显示
   * @param data要格式化的数据 单位byte
   * @return 格式化后的数据,如果小于1M显示单位为KB,如果大于1M显示单位为M
   */
  public String dataFormat(double data){
    String formdata="";
    if (data>=1024*1024) {//大于等于1M
      formdata=Double.toString(data/1024/1024)+"M";
    }else if(data>=1024){//大于等于1KB
      formdata=Double.toString(data/1024)+"KB";
    }else{//小于1KB
      formdata=Double.toString(data)+"byte";
    }
    return formdata.substring(0, formdata.indexOf(".")+2);
  }
}

Client:


 
  
  
  带进度条的文件上传效果
  
  
    
  
  
  
  
  
 
          

带进度条的文件上传效果

  
    文件:          

      

    

    上传进度:0%   
 

Note: In order to prevent the page from jumping after uploading, we can make the form jump to a hidden iframe. I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of the steps for js to request servlet to implement ajax request


AJAX detection without refreshing Entered username

The above is the detailed content of Steps to implement fileUpload upload file with progress bar effect. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn