互联网技术 · 2024年2月28日

Java实现文件上传进度条的简单方法

东西很简单,主要用到commons-fileupload,其中有一个progressListener的接口,该接口可以实现实时更新已上传文件的大小,有了这个还说什么呢?

这里给出代码:

package lc.progress;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import lc.progress.vo.fileUploadStatus;
import org.apache.commons.fileupload.ProgressListener;
public class myProgressListener implements ProgressListener {
  private HttpSession session;
  public myProgressListener(HttpServletRequest req) {
    session=req.getSession();
    fileUploadStatus status = new fileUploadStatus();
    session.setAttribute(“status”, status);
  }
  /* pBytesRead 到目前为止读取文件的比特数
   * pContentLength 文件总大小
   * pItems 目前正在读取第几个文件
   * 只要在session中实时保存文件上传的状态(这里我用fileUploadStatus类来封装)
   */
  public void update(long pBytesRead, long pContentLength, int pItems) {
    // TODO Auto-generated method stub
    fileUploadStatus status = (fileUploadStatus) session.getAttribute(“status”);
    status.setPBytesRead(pBytesRead);
    status.setPContentLength(pContentLength);
    status.setPItems(pItems);
  }
}

然后在上传得servlet或action中加入这样一段代码,就可以把自定义的progressListener添加进去

myProgressListener getBarListener = new myProgressListener(req);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setProgressListener(getBarListener);

最后就是通过js来不断的访问另一个servlet来实时返回上传状态就可以了,限于篇幅我就不再贴代码了,有兴趣的读者可以自己下载来看。

此外,这个代码也可以参考一下:
public static void main(String[] args) throws Exception {
    System.out.print(“Progress:”);
    for (int i = 1; i <= 100; i++) {
        System.out.print(i + “%”);
        Thread.sleep(100);

        for (int j = 0; j <= String.valueOf(i).length(); j++) {
            System.out.print(“b”);
        }
    }
    System.out.println();
}

OpenMagic API

Need more than content? Move into the product flow.

If you are here for model access, pricing, developer docs, or the future API console, the dedicated product path now lives on api.openmagic.ai.

登录免费注册