Thank: http://blog.itpub.net/30066956/viewspace-1773697/ This article refers to a lot of the content of this blog.
Recently, we are writing a video file upload page of our third project to monitor the progress of upload in the background, and then return the monitored information to the front page.
Front-end page rendering:
The foreground progress bar control selects the progressbar control that uses easyui.
Detailed instructions refer to official documents: http://www.jeasyui.com/documentation/index.php
All need to introduce jquery-1.11.1.min.js and jquery.easyui.min.js
I. Front-end code:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'uploadVideo.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <link rel="stylesheet" href="demo.css" /> <link rel="stylesheet" href="easyui.css" /> <link rel="stylesheet" href="icon.css" /> <script type="text/javascript" src="jquery.min.js" ></script> <script type="text/javascript" src="jquery.easyui.min.js" ></script> <link rel="stylesheet" href="videoCss/upload.css" /> <script> $(function() { var pro=0; $("#save").click(function(){ saveDate(); setinterval=setInterval(showUploadProgress, 100); }); function saveDate(){ var form = new FormData(document.getElementById("form")); $.ajax({ type:"POST", url:"uploadfile.action", data:form, async:false, cache:false, processData:false, contentType:false, success:function(result){ var msg=result.msg; $(".msg").text(msg); }, error:function(){ alert("file Asynchronous commit failure"); } }); } function showUploadProgress(){ $.ajax({ type:"GET", url:"uploadProgress.action", dataType:"json", async:false, cache:false, success:function(result){ var progressInfo=result.progressInfo; pro=progressInfo.percent; if(pro==100){ clearInterval(setinterval); } $('#progress').progressbar('setValue', progressInfo.percent); $('progress-bar-status').find(".speed").text(progressInfo.velocity); $('progress-bar-status').find(".finished").text("Uploaded:"+progressInfo.length+"/"+progressInfo.totalLength); $('progress-bar-status').find(".remain").text(progressInfo.timeLeft); }, error:function(result){ alert("error1"); } }); } }); </script> </head> <body> <div class="main_wrapper"> <div class="head_wrapper"> <div class="headinside"> <ul> <li><a href="">master station</a></li> <li><a href="">Video Bar</a></li> <li><a href="">Resource area</a></li> <li><a href="">Personal Center</a></li> </ul> </div> </div><!--head_wrapper End--> <div class="upload_box"> <p id="error"> <s:fielderror name="struts.messages.error.content.type.not.allowed"></s:fielderror> <s:actionerror/> <font color="red" class="msg">${msg }</font> </p> <div class="uploadInfo"> <span class="title"> //Current upload: <span class="filename">file name</span> </span> <div id="progress" class="easyui-progressbar" style="width:400px;"></div> <div class="progress-bar-status"> <span class="speed" style="display: none;">Current upload speed:80.23k/s</span> <span class="finished">Uploaded:10.86M/10.86M</span> <span class="remain" style="display:none">Remaining time:00 second</span> </div> <div class="videoInfo"> <form method="post" enctype="multipart/form-data" id="form"> <ul> <li> <div> <label for="video1">File upload</label> <input type="file" id="btn_file" name="video"/> </div> </li> <li> <label for="name">Title</label> <input type="text" name="name" id="name" title="Title" placeholder="Give your video seven titles"/> </li> <li> <div> <label for="cate">classification</label> <select class="cate" id="cate" name="cate"> <option value ="1">Traditional Literature</option> <option value ="2">folk arts and crafts</option> <option value="3">Day-to-day holidays</option> </select> </div> </li> <li> <div> <label for="tag">Label</label> <input type="text" name="tag" id="tag" placeholder="Please tag your videos accordingly"/> </div> </li> <li> <div> <label for="desc" id="label_desc">describe</label> <textarea name="videoDesc" id="desc" placeholder="Please add the corresponding video description." > </textarea> </div> </li> <input id="save" type="button" value="Preservation"/> <!-- <button id="save">Preservation</button> --> </ul> </form> </div> </div> </div> </div> <div style="width: 100%;"> <div class="footer" style="width: 100%;"> <div class="inner"> <p class="a_menu"> <a target="_blank" rel="nofollow" href="#">About us</a> <i class="line">|</i> <a target="_blank" rel="nofollow" href="#">Contact and Cooperation</a> <i class="line">|</i> <a target="_blank" rel="nofollow" href="#">Help Center</a> <i class="line">|</i> <a target="_blank" rel="nofollow" href="#">Partner Scheme</a> <i class="line">|</i> <a target="_blank" rel="nofollow" href="#">Copyright Declaration</a> </p> <p class="center"> <span>Yaohu Campus of Jiangxi Normal University</span> <span>java Studio</span> <br> copyright© Great white </p> </div> </div> </div> </body> </html>
2. How to get the progress information of the upload after clicking on the upload.
1. Customize an UploadListener class to implement the ProgressListener interface in org.apache.commons.fileupload to obtain the read data length of the currently uploaded file, the total length of the file, and the number of files being saved.
2. Rewrite a MyMultiPartRequest class that covers org. apache. struts2. dispatcher. multipart. Jakarta MultipartRequest, rewrite the parseRequest method, and add a listener to the upload;
3. Define an UploadStatus bean class to store the uploaded status information, and store the UploadStatus object which obtains the uploaded progress information in the Session domain.
4. Write UploadListenAction, get the UploadStatus object in Session domain, process the corresponding data, and then put the required data into Map and return it to jsp in the form of json.
5. Write UploadFile.action to upload and store files;
3. Corresponding code.
package video.action; import org.apache.commons.fileupload.ProgressListener; public class UploadListener implements ProgressListener { private UploadStatus status; public UploadListener(UploadStatus status) { this.status = status; } public void update(long bytesRead, long contentLength, int items) { // The upload component calls this method status.setBytesRead(bytesRead); // Length of read data status.setContentLength(contentLength); // Total length of file status.setItems(items); // How many files are being saved? } }
For the modified method code of MyMultiPartRequest in Step 2.
protected List<FileItem> parseRequest(HttpServletRequest servletRequest, String saveDir) throws FileUploadException { UploadStatus status = new UploadStatus(); // Upload status UploadListener listner = new UploadListener(status); // Monitor servletRequest.getSession().setAttribute("uploadStatus", status);//Store the progress status of the upload in Session; DiskFileItemFactory fac = createDiskFileItemFactory(saveDir); ServletFileUpload upload = createServletFileUpload(fac); upload.setProgressListener(listner);// Adding listeners return upload.parseRequest(createRequestContext(servletRequest)); }
package video.action; public class UploadStatus { private long bytesRead; // The number of bytes uploaded in bytes private long contentLength; // Total length of all files in bytes private int items; // Uploading a few files private long startTime = System.currentTimeMillis(); // Time to start uploading, for calculating upload speed, etc. public long getBytesRead() { return bytesRead; } public void setBytesRead(long bytesRead) { this.bytesRead = bytesRead; } public long getContentLength() { return contentLength; } public void setContentLength(long contentLength) { this.contentLength = contentLength; } public int getItems() { return items; } public void setItems(int items) { this.items = items; } public long getStartTime() { return startTime; } public void setStartTime(long startTime) { this.startTime = startTime; } }
package video.action; import java.util.HashMap; import java.util.Map; import org.apache.struts2.interceptor.SessionAware; import com.opensymphony.xwork2.ActionSupport; public class UploadListenAction extends ActionSupport implements SessionAware{ private UploadStatus status; Map<String,Object> session; Map<String,String> progressInfo=new HashMap<>(); @Override public String execute() throws Exception { // TODO Auto-generated method stub status=(UploadStatus)session.get("uploadStatus"); if(status!=null){ long startTime = status.getStartTime(); //Upload start time long currentTime = System.currentTimeMillis(); //present time long time = (currentTime - startTime)/ 1000 + 1; //Transmitted unit of time:s //Unit of transmission speed:byte/s double velocity = ((double)status.getBytesRead()/1000) / (double)time; //Estimated total time double totalTime = status.getContentLength()/velocity; //Estimate the remaining time double timeLeft = totalTime - time; //Percentage completed int percent = (int)(100 * (double)status.getBytesRead() / (double)status.getContentLength()); //Units completed:m double length = ((double) status.getBytesRead())/1024/1024; //Total length unit:m double totalLength = ((double) status.getContentLength())/1024/1024; progressInfo.put("percent", String.valueOf(percent)); progressInfo.put("velocity", String.valueOf(velocity)); progressInfo.put("totalTime", String.valueOf(totalTime)); progressInfo.put("timeLeft", String.valueOf(timeLeft)); progressInfo.put("length", String.valueOf(length)); progressInfo.put("totalLength", String.valueOf(totalLength)); } return super.execute(); } @Override public void setSession(Map<String, Object> session) { // TODO Auto-generated method stub this.session=session; } public Map<String, String> getProgressInfo() { return progressInfo; } /*public UploadStatus getStatus() { return status; }*/ }
package video.action; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; import javax.servlet.ServletContext; import org.apache.commons.io.FileUtils; import org.apache.struts2.ServletActionContext; import org.apache.struts2.interceptor.SessionAware; import video.dao.UploadDao; import video.daoimpl.UploadDaoImpl; import videomodel.VideoInfo; import cn.history.pojo.User; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; public class UploadFile extends ActionSupport{ private static final long serialVersionUID = 4182168930616232826L; private String name; //Title Name private File video; private String videoFileName; private String videoContentType; private String videoDesc; //describe private int cate; //type private String tag; //Label /*private VideoInfo videoInfo=new VideoInfo();*/ private String msg; private UploadDao uploadDao=new UploadDaoImpl(); public String upload() throws Exception{ //Complete upload ServletContext sc=ServletActionContext.getServletContext(); String directory=sc.getRealPath("/video");//It's really a directory that gets the files stored. //Depending on the type of video, it is stored in different directories if(cate==1){ //If it's traditional literature directory=directory+"/guoxue"; }else if(cate==2){ directory=directory+"/minjian"; }else{ directory=directory+"/jiari"; } SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmssS");//Formatting time output String Rname=null; if(name!=null&&!name.equals("")){ Rname=name+"_"+sdf.format(new Date())+".mp4"; }else{ Rname=videoFileName; } System.out.println(Rname); //Building target files File target=new File(directory,Rname); FileUtils.copyFile(video, target); System.out.println(Rname+"\n"+videoFileName+"\n"+videoDesc+"\n"+videoContentType); //Save basic information of successfully uploaded video to database m String filePath=target.getPath(); filePath=filePath.substring(filePath.indexOf("video")).replace("\\", "/"); System.out.println(filePath); VideoInfo videoInfo=new VideoInfo(); videoInfo.setVideoName(Rname); videoInfo.setVideoDesc(videoDesc); videoInfo.setVideoUrl(filePath); videoInfo.setCate(cate); videoInfo.setTag(tag); //ActionContext.getContext().getSession().get("name"); if(ActionContext.getContext().getSession().get("user")!=null){ User user=(User) ActionContext.getContext().getSession().get("user"); videoInfo.setAuthorId(user.getUser_id()); }else{ //Set to Administrator id,Administrator uploads by default videoInfo.setAuthorId(1); } int tag=uploadDao.saveVideo(videoInfo); if(tag==0){ msg="Upload failure(Storage database procedure error)"; return INPUT; }else{ msg="Video upload success"; } return SUCCESS; } /* public VideoInfo getVideoInfo() { return videoInfo; } public void setVideoInfo(VideoInfo videoInfo) { this.videoInfo = videoInfo; }*/ /*public String getName() { return name; }*/ public void setName(String name) { this.name = name; } // public File getVideo() { // return video; // } public void setVideo(File video) { System.out.println(video); this.video = video; } // public String getVideoDesc() { // return videoDesc; // } public void setVideoDesc(String videoDesc) { this.videoDesc = videoDesc; } /*public int getCate() { return cate; }*/ public void setCate(int cate) { this.cate = cate; } /*public String getTag() { return tag; }*/ public void setTag(String tag) { this.tag = tag; } // public String getVideoFileName() { // return videoFileName; // } public void setVideoFileName(String videoFileName) { this.videoFileName = videoFileName; } /*public String getVideoContentType() { return videoContentType; }*/ public void setVideoContentType(String videoContentType) { this.videoContentType = videoContentType; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }