Implement file upload with progress bar and Ajax File Upload Based on ajax technology

Source: Internet
Author: User
Tags file upload progress bar

Implement file upload with progress bar and Ajax File Upload Based on ajax technology

1. Overview

In actual Web development or website development, file upload is often required. During file upload, users often need to wait for a long time. To keep users updated on the upload progress, you can display the File Upload progress bar while uploading the file. Run this instance, as shown in Figure 1. Visit the file upload page and click the Browse button to select the file to be uploaded. Note that the file size cannot exceed 50 MB. Otherwise, an error message is displayed. After selecting the file to be uploaded, click Submit to upload the file and display the upload progress.

2. Key Technical Points

It mainly applies the open-source Common-FileUpload component to implement multipart file upload, so as to continuously obtain the upload progress during the upload process. The following describes the Common-FileUpload component in detail.

The Common-FileUpload component is a subproject under the jakarta-commons project in the Apache organization. This component can easily parse various form fields in multipart/form-data requests. This component must be supported by another component named "Common-IO. These two package files can be downloaded on the website.

(1) Create an upload object

When the Common-FileUpload component is used to upload files, you must create a factory object and create a new file upload object based on the factory object. The Code is as follows:

DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory); 

(2) Parse upload requests

After creating a file upload object, you can apply this object to parse the upload request and obtain all the form items. This can be achieved through 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 file fields and Common form fields are processed as FileItem objects. If the isFormField () method of this object returns true, it indicates a common form field; otherwise, it is a file field. To upload a file, you can use the getName () method of the FileItem class to obtain the file name and the getSize () method to obtain the size of the file to be uploaded.

3. Specific implementation

(1) create a request. js file, and write the Ajax request Method in the file.

(2) create a file upload page index. jsp, add the form and form elements used to obtain the information of the uploaded file, and add the <div> label and <span> label used to display the progress bar, the key code is as follows:

<form enctype="multipart/form-data" method="post" action="UpLoad?action=uploadFile">

Select the uploaded file: <input name = "file" type = "file" size = "34">

Note: The file size must be within 50 MB.

<div id="progressBar" class="prog_border" align="left">
<img src="images/progressBar.gif" width="0" height="13" id="imgProgress"></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) create a Servlet implementation class UpLpad for uploading files. Compile the uploadFile () method to implement file upload in this class. In this method, use the Common-FileUpload component to implement multipart file upload, calculate the upload percentage, and save it to the Session in real time, the key code is as follows:

public void uploadFile(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session=request.getSession();
Session. SetAttribute ("ProgressBar", 0); / / defines the session variable specifying the upload progress
String error = "";
Int maxsize = 50 * 1024 * 1024; / / upper limit of single upload file size
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 the upload request
Iterator ITR = items. Iterator(); / / enumeration method
while (itr.hasNext()) {
Fileitem item = (fileitem) ITR. Next(); / / get fileitem object
If (! Item. Isformfield()) {/ / determine whether it is a file field
If (item. Getname()! = null &amp; &amp;! Item. Getname(). Equals ("") {/ / whether the file is selected
Long upfilesize = item. Getsize(); / / the size of the uploaded file
String filename = item. Getname(); / / get the filename
Error = "the file you uploaded is too large, please select a file no more than 50m";
//At this time, the file is temporarily stored in the memory of the server
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; / / defines the size of the buffer
int length=0;
byte[] b=new byte[buffer];
double percent=0;
FileOutputStream fos=new FileOutputStream(file);
Percentage + = length / (double) upfilesize * 100D; / / calculate the percentage of uploaded files
FOS. Write (B, 0, length); / / write the read data to the file output stream
Fos.close ();
Thread.sleep (1000); / / thread sleep for 1 second
} else {
Error = "no upload file selected! ";
} catch (Exception e) {
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) index on the file upload page. in jsp, import the prepared Ajax request Method request. js file, 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;
function getProgress(){
Var url = "showprogress. JSP"; / / server address
Var param = "nocache =" + new date(). Gettime(); / / the URL parameters of each request are different, so as to avoid the progress bar not moving when uploading
Request = httprequest ("post", URL, true, callbackfunc, param); / / call the request method
//Ajax callback function
function callbackFunc(){
If (request. ReadyState = = 4) {/ / judge whether the response is complete
If (request. Status = = 200) {/ / judge whether the response is successful
Var H = request.responsetext; / / get the returned response data, which is the percentage of upload progress
H = h.replace (/ \ s / g, ""); / / remove the Unicode whitespace in the string
Document. Getelementbyid ("progresspercent"). Style. Display =; / / display percentage
Progresspercent. InnerHTML = H + "%"; / / displays the percent complete
Document. Getelementbyid ("ProgressBar"). Style. Display = "block"; / / display progress bar
Document. Getelementbyid ("imgprogress"). Width = h * (235 / 100); / / display the progress of completion

(5) Compile the showProgress. jsp page. on this page, apply the EL expression to output the value of the upload progress bar saved in the session field. The Code is as follows:

<%@page contentType="text/html" pageEncoding="GBK"%>

(6) Compile the JavaScript method called by the onclick event of the Form submission button. In this method, the setInterval () method of the window Object Requests the server every certain time to obtain the latest upload progress, the key code is as follows:

function deal(form){
Form. Submit(); / / submit the form
Timer = window.setinterval ("getprogress()", 500); / / get the upload progress every 500 milliseconds

The above section describes how to implement file upload with a progress bar based on Ajax technology. I hope it will be helpful to you. If you have any questions, please leave a message for me, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

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: 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.