This article describes the implementation method of uploading a file progress bar in Java. Share it for your reference, as follows:
The thing is very simple, mainly using commons-fileupload, which has a progressListener interface, which can achieve real-time update of the size of uploaded files. What else can I say with this?
Here is the code:
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 The number of bits read files so far * pContentLength Total file size * pItems how many files are currently being read * Just save the status of file upload in the session in real time (here I use the fileUploadStatus class to encapsulate) */ 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); }}Then add such a piece of code to the upload servlet or action, and you can add the custom progressListener to
myProgressListener getBarListener = new myProgressListener(req);ServletFileUpload upload = new ServletFileUpload(factory);upload.setProgressListener(getBarListener);
Finally, I can use js to continuously access another servlet to return to the upload status in real time. Due to space limitations, I will no longer post code. Interested readers can download it by themselves.
Click here to download the complete example code.
I hope this article will be helpful to everyone's Java programming.