1. Overview
In the actual web should be developed or Web site development process, often need to implement the function of file upload. In the file upload process, often require users to wait for a long time, in order to allow users to understand the upload progress, you can upload files at the same time, display the file upload progress bar. Run this example, 1, access the File upload page, click the "Browse" button to select the file to upload, note that the file must not exceed 50MB, or the system will give an error message. After selecting the file to upload, click the "Submit" button, the file will be uploaded and the upload progress can be displayed.
2. Technical Highlights
The main application of open source Common-fileupload components to achieve multipart file upload, in order to achieve in the upload process, and constantly get upload progress. The Common-fileupload components are described in more detail below.
The Common-fileupload component is a subproject under the Jakarta-commons project under the Apache organization that can easily resolve various form fields in a Multipart/form-data type request. This component requires support for another component named Common-io. These two component package files can be downloaded to the http://commons.apache.org Web site.
(1) Create an Upload object
When you should implement a file upload for a common-fileupload component, you need to create a factory object and create a new file upload object based on the factory object, with the following code:
Newnew servletfileupload (factory);
(2) Resolve upload request
After creating a file upload object, you can apply the object to resolve the upload request and get all the form items, which can be implemented by the Parserequest () method of the file upload object. The syntax structure of the Parserequest () method is as follows:
Public List parserequest (HttpServletRequest request) throws Fileuploadexception
(3) Fileitem class
In the Common-fileupload component, both the file field and the normal form field are treated as Fileitem objects. If the object's Isformfield () method returns a value of true, it is a normal form field, otherwise a file field. In the implementation of file upload, you can obtain the file name of the uploaded file through the GetName () method of the Fileitem class, and get the size of the uploaded file through the GetSize () method.
3. Concrete implementation
(1) Create the Request.js file, and write the Ajax request method in the file.
(2) Create a new File upload page index.jsp, add a form and form element for uploading file information on this page, and add a <span> tag to display the <div> label and display percentage of the progress bar, the key code is as follows:
<form enctype= "Multipart/form-data" method= "post" action= "Upload?action=uploadfile" > Please select the uploaded file: <input name= "File" type= "file" size= "> Note: File size please control within 50M. <div id= "ProgressBar" class= "Prog_border" align= "left" > </div> <span id=" progresspercent "style=" Width:40px;display : None ">0%</span> <input name=" Submit "type=" button "value=" Submit "onclick=" Deal (This.form) "> <input name= "reset" type= "reset" class= "Btn_grey" value= "reset" ></td></form>
(3) The Servlet implementation class Uplpad for the new upload file. In this class to write the implementation of the file Upload Method UploadFile (), in the method through the Common-fileupload component implementation of multipart upload file, and calculate the upload percentage, real-time saved to the session, the key code is as follows:
PublicvoidUploadFile (httpservletrequest request, httpservletresponse response) throws Servletexception, IOException { Response.setcontenttype ("TEXT/HTML;CHARSET=GBK"); Request.setcharacterencoding ("GBK"); HttpSession Session=request.getsession (); Session.setattribute ("ProgressBar", 0);//defines the session variable that specifies the upload progressString error = ""; intmaxsize=50*1024*1024;//maximum size of a single upload fileDiskfileitemfactory factory =NewDiskfileitemfactory ();//Create a Factory objectServletfileupload upload =NewServletfileupload (Factory);//Create a new File upload object Try{List Items= Upload.parserequest (request);//Parsing upload RequestsIterator ITR = Items.iterator ();//Enumeration Methods while(Itr.hasnext ()) {Fileitem Item= (Fileitem) itr.next ();//Get Fileitem Object if(!item.isformfield ()) {//Determine if the file field if(Item.getname ()! =NULL&&!item.getname (). Equals ("")) {//whether the file is selected LongUpfilesize=item.getsize ();//size of uploaded fileString Filename=item.getname ();//Get file name if(upfilesize>maxSize) {Error= "The file you uploaded is too large, please select No more than 50M files"; Break; } //the file temporarily exists in the server's memoryFile tempfile =NewFile (FileName);//constructing a file directory temporary objectString Uploadpath = This. Getservletcontext (). Getrealpath ("/upload"); File File=NewFile (Uploadpath,tempfile.getname ()); InputStream is=Item.getinputstream (); intbuffer=1024;//define the size of the buffer intLength=0; byte[] b=New byte[buffer]; DoublePercent=0; FileOutputStream Fos=Newfileoutputstream (file); while((Length=is.read (b))!=-1) {percent+=length/(double) upfilesize*100d; Calculates the percentage of uploaded files Fos.write (b,0,length);//write-read data to the file output streamSession.setattribute ("ProgressBar", Math.Round (percent)); } fos.close (); Thread.Sleep (1000);//thread hibernation 1 seconds}Else{Error= "no option to upload files!" "; } } } } Catch(Exception e) {e.printstacktrace (); Error= "An error occurred uploading the file:" +E.getmessage (); } if(!"". Equals (Error)) {Request.setattribute ("Error", error); Request.getrequestdispatcher ("Error.jsp"). Forward (request, response); }Else{Request.setattribute ("Result", "File Upload succeeded!" "); Request.getrequestdispatcher ("Upfile_deal.jsp"). Forward (request, response); }}
(4) In the File upload page index.jsp, import the Request.js file of the Ajax request method written, and write the Ajax request method and Ajax callback function to get the upload progress, the key code is as follows:
<script language= "javascript" src= "js/request.js" ></script><script language= "JavaScript" >varRequest =false;functiongetprogress () {varUrl= "showprogress.jsp";//Server Address varparam = "nocache=" +NewDate (). GetTime ();//each request URL parameter is different, avoid the progress bar not moving when uploadingRequest=httprequest ("Post", URL,true, Callbackfunc,param);//Call Request Method}//Ajax callback functionfunctionCallbackfunc () {if(request.readystate==4) {//determine if the response is complete if(Request.status = = 200) {//determine if the response was successful varh = request.responsetext;//gets the response data returned, the percentage of the data bit upload progressH=h.replace (/\s/g, "");//to remove Unicode whitespace characters from a stringdocument.getElementById ("Progresspercent"). style.display= "";//Show Percentagesprogresspercent.innerhtml=h+ "%";//show percentage of completiondocument.getElementById ("ProgressBar"). style.display= "Block";//Show progress bardocument.getElementById ("Imgprogress"). width=h* (235/100); Show progress on completion } }}</script>
(5) Write the showprogress.jsp page where the EL expression is used to output the value of the upload progress bar stored in the session field, as follows:
<% @page contenttype= "text/html" pageencoding= "GBK"%>${progressbar}
(6) Write the form submit button onclick event called by the JavaScript method, the method through the Window object's SetInterval () method to request a server at a certain time, to obtain the latest upload progress, the key code is as follows:
function Deal (form) { form.submit (); // Submit Form Timer=window.setinterval ("getprogress ()", +); // get the upload progress every 500 milliseconds }
Ajax technology-File upload with progress bar