Implementation of file upload with progress bar _ajax correlation based on AJAX technology

Source: Internet
Author: User
Tags file upload file upload progress bar setinterval


1. Overview



In the actual web should be developed or web development process, often need to implement the file upload function. In the file upload process, often require users to wait for a long time, in order to allow users to timely understand upload progress, you can upload files at the same time, display file upload progress bar. Run this example, as shown in Figure 1, access to the File upload page, click the "Browse" button to select the file to upload, note that the file can not exceed 50MB, or the system will give error prompts. When you have finished selecting the file you want to upload, click the Submit button, and the file will be uploaded and the upload progress displayed.



2. Technical points



Mainly uses the open source Common-fileupload component to realize the segmented file uploads, thus realizes in the upload process, unceasingly obtains uploads the progress. The Common-fileupload components are described in detail below.



The Common-fileupload component is a subproject under the Jakarta-commons project in Apache, which makes it easy to resolve various form fields in a Multipart/form-data type request. This component requires the support of another component named Common-io. These two component package files can be downloaded on the http://commons.apache.org Web site.



(1) Create uploaded objects



When you should common-fileupload the component implementation file upload, you need to create a factory object and create a new file upload object based on the factory object, as follows:


Diskfileitemfactory factory = new Diskfileitemfactory ();


(2) Resolution of the upload request

After creating a file upload object, you can apply the object to resolve the upload request, get all the form items, 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, either a file field or a normal form field is treated as a Fileitem object. 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 use the Fileitem class GetName () method to obtain the file name of the uploaded file, through the GetSize () method to obtain the size of the uploaded file.



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 to get the uploaded file information on the page, and add a <span> label that displays the <div> label and percentage of the progress bar, with the following key codes:


<form enctype= "Multipart/form-data" method= "post" action= "Upload?action=uploadfile" >


Please select the file to upload: <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>


(3) New upload file of the Servlet implementation class Uplpad. In this class to write the implementation of File upload Method UploadFile (), in this method through the Common-fileupload component implementation of the segmented upload file, and calculate the upload percentage, real-time save to session, the key code is as follows:


public void uploadFile (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType ("text / html; charset = GBK");
request.setCharacterEncoding ("GBK");
HttpSession session = request.getSession ();
session.setAttribute ("progressBar", 0); // Define a session variable that specifies the upload progress
String error = "";
int maxSize = 50 * 1024 * 1024; // Maximum size of a single upload file
DiskFileItemFactory factory = new DiskFileItemFactory (); // Create factory object
ServletFileUpload upload = new ServletFileUpload (factory); // Create a new file upload object
try {
List items = upload.parseRequest (request); // Parse upload request
Iterator itr = items.iterator (); // enum method
while (itr.hasNext ()) {
FileItem item = (FileItem) itr.next (); // Get FileItem object
if (! item.isFormField ()) {// determine if it is a file field
if (item.getName ()! = null &&! item.getName (). equals ("")) {// Whether a file is selected
long upFileSize = item.getSize (); // size of uploaded file
String fileName = item.getName (); // Get the file name
if (upFileSize> maxSize) {
error = "The file you uploaded is too large, please select a file no larger than 50M";
break;
}
// At this point the file is temporarily stored in the server's memory
File tempFile = new File (fileName); // Construct file directory temporary object
String uploadPath = this.getServletContext (). GetRealPath ("/ upload");
File file = new File (uploadPath, tempFile.getName ());
InputStream is = item.getInputStream ();
int buffer = 1024; // define buffer size
int length = 0;
byte [] b = new byte [buffer];
double percent = 0;
FileOutputStream fos = new FileOutputStream (file);
while ((length = is.read (b))! =-1) {
percent + = length / (double) upFileSize * 100D; // Calculate the percentage of uploaded files
fos.write (b, 0, length); // write read data to file output stream
session.setAttribute ("progressBar", Math.round (percent));
}
fos.close ();
Thread.sleep (1000); // Thread sleeps for 1 second
} else {
error = "No file selected to upload!";
}
}
}
} catch (Exception e) {
e.printStackTrace ();
error = "Error uploading file:" + e.getMessage ();
}
if (! "". equals (error)) {
request.setAttribute ("error", error);
request.getRequestDispatcher ("error.jsp"). forward (request, response);
} else {
request.setAttribute ("result", "File uploaded successfully!");
request.getRequestDispatcher ("upFile_deal.jsp"). forward (request, response);
}
}


(4) In the File upload page index.jsp, import the written Ajax request method Request.js file, and write the upload progress of the Ajax request method and Ajax callback function, the key code is as follows:


<script language = "javascript" src = "js / request.js"> </ script>
<script language = "javascript">
var request = false;
function getProgress () {
var url = "showProgress.jsp"; // Server address
var param = "nocache =" + new Date (). getTime (); // The URL parameters are different each time, to avoid the progress bar from moving when uploading
request = httpRequest ("post", url, true, callbackFunc, param); // call request method
}
// Ajax callback function
function callbackFunc () {
if (request.readyState == 4) {// Determine whether the response is complete
if (request.status == 200) {// determine whether the response was successful
var h = request.responseText; // Get the response data returned, which is the percentage of upload progress
h = h.replace (/ \ s / g, ""); // Remove Unicode whitespace from the string
document.getElementById ("progressPercent"). style.display = ""; // Display percentage
progressPercent.innerHTML = h + "%"; // Show percentage completed
document.getElementById ("progressBar"). style.display = "block"; // Show progress bar
document.getElementById ("imgProgress"). width = h * (235/100); // Show progress of completion
}
}
}
</ script>  


(5) Write showprogress.jsp page, in which the El expression output is saved in the session domain upload progress bar value, the specific code is as follows:


<% @page contenttype= "text/html" pageencoding= "GBK"%>


(6) Write the JavaScript method invoked by the form submission button onclick event, where the server is requested at a certain time by the SetInterval () method of the Window object to obtain the latest upload progress, the key code is as follows:


Function deal (form) {
form.submit ();//Submit Form
Timer=window.setinterval ("getprogress ()", 500);// Get upload progress every 500 milliseconds
}


The above is a small set to introduce Ajax technology based on the implementation of file upload with progress bar related knowledge, hope to help everyone, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!


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.