Servlet + jquery implements the sample code of the file upload progress bar, servletjquery

Source: Internet
Author: User
Tags file upload progress bar

Servlet + jquery implements the sample code of the file upload progress bar, servletjquery

Currently, progress bars are required for file uploads, especially for large files, so that you can know the upload progress.

This article briefly records how to get the progress bar and some upload information, such as the file size, upload speed, estimated remaining time, and other related information. The code is written in a rush, and some verification is not done, or the Code has some hidden dangers and is not rigorous. The code in this article is for reference only.

The progress bar has a variety of styles, and some websites are very gorgeous and beautiful. I don't know much about the UI in this article. I only need some simple basic css, so the progress bar is hard to understand. This article focuses on providing readers with a reference and an implementation idea.

Note: Because the jQuery version is 2.1.1, if you run the source code of this example, use IE9 or above or Firefox or Google browser for testing.

 

Servlet for Receiving File Uploads

UploadFileServlet. Java

Package com. fei. servlet; import java. io. IOException; import java. util. date; import java. util. map; import javax. servlet. servletException; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import com. fei. util. fileUploadUtil; public class UploadFileServlet extends HttpServlet {private static final long serialVersionUID = 1L; public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this. doPost (request, response);} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {try {long start = System. currentTimeMillis (); System. out. println ("start uploading files ......... "); Map <String, String> params = FileUploadUtil. upload (request); System. out. println ("the file has been uploaded ......... "); System. out. println ("Last file time:" + (System. currentTimeMillis ()-start) + "millisecond");} catch (Exception e) {e. printStackTrace ();}}}

Download uploaded files to the server

FileUploadUtil. java

Package com. fei. util; import java. io. file; import java. util. hashMap; import java. util. iterator; import java. util. list; import java. util. map; import javax. servlet. http. httpServletRequest; import org. apache. commons. fileupload. fileItem; import org. apache. commons. fileupload. progressListener; import org. apache. commons. fileupload. disk. diskFileItemFactory; import org. apache. commons. fileupload. servlet. servletFileUpload; public class FileUploadUtil {/*** file upload and storage path */private static final String SAVE_FILEPATH = "/fileupload /"; /*** temporary storage path for file upload */private static final String SAVE_FILE_TMPPATH = "/fileupload/tmp /"; /*** maximum size of the uploaded file */private static final int MAX_FILE_SIZE = 100*1024*1024;/*** after how many MB of file data exceeds the memory, write the temporary file */private static final int THRESHOLD_SIZE = 2*1024*1024; private static final String ENCODING = "UTF-8 "; /*** process the File Upload form * to download the file, and return the file name and other attribute values in the common form field * get the file name */public static Map <String, string> upload (HttpServletRequest request) throws Exception {Map <String, String> params = new HashMap <String, String> (); String savePath = request. getSession (). getServletContext (). getRealPath (SAVE_FILEPATH) + File. separator; String savePathTemp = request. getSession (). getServletContext (). getRealPath (SAVE_FILE_TMPPATH) + File. separator; File saveFileTempDir = new File (savePathTemp); DiskFileItemFactory factory = new DiskFileItemFactory (); // when the File data in the memory reaches THRESHOLD_SIZE, it is written to the temporary File, avoid Overconsuming the factory memory when uploading large files. setSizeThreshold (THRESHOLD_SIZE); factory. setRepository (saveFileTempDir); ServletFileUpload upload = new ServletFileUpload (factory); upload. setHeaderEncoding (ENCODING); upload. setSizeMax (MAX_FILE_SIZE); FileUploadInfo fileUploadInfo = new FileUploadInfo (); upload. setProgressListener (new FileUploadListener (fileUploadInfo); request. getSession (). setAttribute ("uploadInfo", fileUploadInfo); List items = upload. parseRequest (request); Iterator iter = items. iterator (); int fileNum = 1; while (iter. hasNext () {FileItem item = (FileItem) iter. next (); if (item. isFormField () {// common form field params. put (item. getFieldName (), item. getString ();} else {String fileName = item. getName (). replace ("/", "\"); int I = fileName. lastIndexOf ("\"); fileName = fileName. substring (I + 1); // avoid repeating fileName = System. currentTimeMillis () + fileName; File uploadedFile = new File (savePath + fileName); item. write (uploadedFile); params. put ("fileName0" + fileNum, fileName); fileNum ++;} return params;} class FileUploadListener implements ProgressListener {FileUploadInfo fileUploadInfo = null; public FileUploadListener (FileUploadInfo fileUploadInfo) {this. fileUploadInfo = fileUploadInfo;} @ Override public void update (long uploadSize, long totalSize, int itemNum) {this. fileUploadInfo. setTotalSize (totalSize); this. fileUploadInfo. setUploadSize (uploadSize );}}

Upload File Information

FileUploadInfo. java

Package com. fei. util; public class FileUploadInfo {private final int K = 1024; private final int M = K * 1024;/*** total size */private long totalSize; /*** start upload time */private long startTime = System. currentTimeMillis ();/*** Number of uploaded files */private long uploadSize;/*** upload speed (K/S) */public double getUploadSpeed_K () {long currentTime = System. currentTimeMillis (); long usedTime = currentTime-startTime; if (UsedTime = 0.0) {return 0.0;} return getUploadSize_K ()/usedTime * 1000d;}/*** get the uploaded percentage * @ return */public double getUploadPercent () {return (getUploadSize () * 1.00/getTotalSize () * 100d;}/*** remaining time (s) * @ return */public double getRemainTime () {double speedKB = getUploadSpeed_K (); if (speedKB <= 0.00) {return-1d;} return (getTotalSize_K ()-getUploadSize_K ()/speedKB ;} /*** uploaded time ** @ return * /Public double getUseTime () {return (System. currentTimeMillis ()-startTime)/1000d;} public long getTotalSize () {return totalSize;} public double getTotalSize_K () {return getTotalSize () * 1.0/K ;} public double getTotalSize_M () {return getTotalSize () * 1.0/M;} public long getUploadSize () {return uploadSize;} public double getUploadSize_K () {return getUploadSize ()/K ;} public double getUploadSiz E_M () {return getUploadSize ()/M;} public void setTotalSize (long totalSize) {this. totalSize = totalSize;} public void setUploadSize (long uploadSize) {this. uploadSize = uploadSize;} private String double2String (double d) {return String. format ("%. 2f ", d);} public String toString () {return" {"+" 'totalsize': '"+ double2String (getTotalSize_M () +" M ', "+" 'uploadsize': '"+ double2String (getUploadSize_M () + "M'," + "'uploadspeed': '" + double2String (getUploadSpeed_K () + "KB/s'," + "'uploadprecent ': '"+ double2String (getUploadPercent () +"', "+" 'remaintime': '"+ (getRemainTime () <0? "Unknown": double2String (getRemainTime () + "s" + "'," + "'usetime':'" + double2String (getUseTime ()) + "S'" + "}";}}

Servlet for reading the File Upload progress

UploadFileProgressServlet. java

Package com. fei. servlet; import java. io. IOException; import javax. servlet. servletException; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import com. fei. util. fileUploadInfo; public class UploadFileProgressServlet extends HttpServlet {private static final long serialVersionUID = 1L; public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this. doPost (request, response);} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String responseContent = ""; Object obj = request. getSession (). getAttribute ("uploadInfo"); if (obj = null) {responseContent = "{'data': 'nodata'}";} else {FileUploadInfo uploadInfo = (FileUploadInfo) obj; responseContent = uploadInfo. toString (); if (uploadInfo. getUploadPercent () == 100.0) {request. getSession (). setAttribute ("uploadInfo", null) ;}} System. out. println ("Last file:" + responseContent); response. getWriter (). print (responseContent );}}

Front page upload2.html

<! DOCTYPE html> 

Deploy the project to tomcat (or other web containers) and access http: // 172.16.126.128: 8080/uploadtest/upload2.html

Effect:


Download Code: demo

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.