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: Please control the file size 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 {resp Onse.setcontenttype ("TEXT/HTML;CHARSET=GBK"); Request.setcharacterencoding ("GBK"); HttpSession session=Request.getsession (); Session.setattribute ("ProgressBar", 0);//Defines the session variable that specifies the upload progress String error = "";int maxsize=50*1024*1024;//Maximum single upload file size diskfileitemfactory factory =New Diskfileitemfactory ();//Create Factory object Servletfileupload upload =New Servletfileupload (Factory);//Create a new File upload objectTry{List items = upload.parserequest (request);//Parse Upload request Iterator ITR = Items.iterator ();//Enumeration methodsWhile(Itr.hasnext ()) {Fileitem item = (Fileitem) itr.next ();//Get Fileitem Objectif (!item.isformfield ()) {//Determine if the file fieldif (Item.getname ()! =Null &&!item.getname (). Equals ("")) {//Whether the file is selectedLong Upfilesize=item.getsize ();//Size of the uploaded file String filename=item.getname ();//Get file nameif (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 in-memory files Tempfile =New File (FileName);//Construct file Directory Temp object String Uploadpath =This.getservletcontext (). Getrealpath ("/upload"); File File =NewFile (Uploadpath,tempfile.getname ()); InputStream is=Item.getinputstream ();int buffer=1024;//Define the size of the bufferint length=0;Byte[] B=NewByte[Buffer];Double percent=0; FileOutputStream fos=NewFileOutputStream (file);while ((Length=is.read (b))!=-1{percent+=length/(double) upfilesize*100d;//Calculate the percentage of uploaded files Fos.write (b,0,length);//Writes read data to the file output stream Session.setattribute ("ProgressBar", Math.Round (percent)); } fos.close (); Thread.Sleep (1000);// thread sleeps 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" ). Forward (request, response); }else {Request.setattribute ("result", "File Upload succeeded!") "); Request.getrequestdispatcher ("upfile_deal.jsp"
(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" >var request =False;functionGetprogress () {var url= "showprogress.jsp";//Server addressvar param = "nocache=" +New Date (). GetTime ();//Each request URL parameter is different, avoid the progress bar when uploading request=httprequest ("post", URL,True,callbackfunc,param);//Call Request method}//Ajax callback functionfunctionCallbackfunc () {if (request.readystate==4) {//Determine if the response is completeif (Request.status = =) {// to determine if the response was successful var h = request.responsetext; // Gets the response data returned, the data bit upload progress percentage h=h.replace (/\s/g, ""); // remove the Unicode whitespace character from the string document.getElementById (" Progresspercent "). style.display=" "; //////}}}</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 ()", +); // every 500 milliseconds to get the upload progress}
Ajax technology-File upload with progress bar