Advertisement

01.12.2008 at 04:00AM PST, ID: 23077798
[x]
Attachment Details

AJAX, common fileupload progressbar, help me to run example

Asked by Igor_Sand in WebApplications, JavaScript, Java Servlets

Tags: JSP, Java, AJAX, JavaScript, IE 7.0, Firefox

Dear experts!
I have a little problem with following AJAX file upload example using servlet mechanism...
I'he setting up the exampe, everything works fine, file is creating on remote machine, but there is something strange with progress bar...
In IE 7.0 browser, when i press submit button, i got only "Initializing upload..." <div> in browser.
In firefox, when i open page for the first time and press submit button, browser sending file, and shows me "Done" <div>. When i click on submit button again, i can see progress of upload process!!!
Please, help me to solve this problem with this example. I've spent already 2 weeks on this issue!
PS: sorry for my English...Start Free Trial
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
216:
217:
218:
219:
220:
221:
222:
223:
224:
225:
226:
227:
228:
229:
230:
231:
232:
233:
234:
235:
236:
237:
238:
239:
240:
241:
242:
243:
244:
245:
246:
247:
248:
249:
250:
251:
252:
253:
254:
255:
256:
257:
258:
259:
260:
261:
262:
263:
264:
265:
266:
267:
268:
269:
270:
271:
272:
273:
274:
275:
276:
277:
278:
279:
280:
281:
282:
283:
284:
285:
286:
287:
288:
289:
290:
291:
292:
293:
294:
295:
296:
297:
298:
299:
300:
301:
302:
303:
304:
305:
306:
307:
308:
309:
310:
311:
312:
313:
314:
315:
316:
317:
318:
319:
320:
321:
322:
323:
324:
325:
326:
327:
328:
329:
330:
331:
332:
333:
334:
335:
336:
337:
338:
339:
340:
341:
342:
343:
344:
345:
346:
347:
348:
349:
350:
351:
352:
353:
354:
355:
356:
357:
358:
359:
360:
361:
362:
363:
364:
365:
366:
367:
368:
369:
370:
371:
372:
373:
this is title html page:
<html> 
<head> 
<title>Ajax File Upload</title> 
<script language="javascript"> 
var req; 
 
function ajaxFunction() 
{ 
   var url = "http://stip-nb.ad.inside.mts.ru:8080/AJAXFileUpload/FileUploadServlet"; 
    
   if (window.XMLHttpRequest) // Non-IE browsers 
   { 
      req = new XMLHttpRequest(); 
      req.onreadystatechange = processStateChange; 
 
      try 
      { 
         req.open("GET", url, true); 
      } 
      catch (e) 
      { 
         alert(e); 
      } 
      req.send(null); 
   } 
   else if (window.ActiveXObject) // IE Browsers 
   { 
      req = new ActiveXObject("Microsoft.XMLHTTP"); 
    
      if (req) 
      { 
         req.onreadystatechange = processStateChange; 
         req.open("GET", url, true); 
         req.send(); 
      } 
   } 
} 
 
function processStateChange() 
{ 
   /** 
    *   State   Description 
    *   0      The request is not initialized 
    *   1      The request has been set up 
    *   2      The request has been sent 
    *   3      The request is in process 
    *   4      The request is complete 
    */ 
   if (req.readyState == 4) 
   { 
      if (req.status == 200) // OK response 
      { 
         var xml = req.responseXML; 
 
         // No need to iterate since there will only be one set of lines 
         var isNotFinished = xml.getElementsByTagName("finished")[0]; 
         var myBytesRead = xml.getElementsByTagName("bytes_read")[0]; 
         var myContentLength = xml.getElementsByTagName("content_length")[0]; 
         var myPercent = xml.getElementsByTagName("percent_complete")[0]; 
 
         // Check to see if it's even started yet 
         if ((isNotFinished == null) && (myPercent == null)) 
         { 
            document.getElementById("initializing").style.visibility = "visible"; 
 
            // Sleep then call the function again 
            window.setTimeout("ajaxFunction();", 100); 
         } 
         else 
         { 
            document.getElementById("initializing").style.visibility = "hidden"; 
            document.getElementById("progressBarTable").style.visibility = "visible"; 
            document.getElementById("percentCompleteTable").style.visibility = "visible"; 
            document.getElementById("bytesRead").style.visibility = "visible"; 
 
            myBytesRead = myBytesRead.firstChild.data; 
            myContentLength = myContentLength.firstChild.data; 
 
            if (myPercent != null) // It's started, get the status of the upload 
            { 
               myPercent = myPercent.firstChild.data; 
       
               document.getElementById("progressBar").style.width = myPercent + "%"; 
               document.getElementById("bytesRead").innerHTML = myBytesRead + " of " + 
                  myContentLength + " bytes read"; 
               document.getElementById("percentComplete").innerHTML = myPercent + "%"; 
    
               // Sleep then call the function again 
               window.setTimeout("ajaxFunction();", 100); 
            } 
            else 
            { 
               document.getElementById("bytesRead").style.visibility = "hidden"; 
               document.getElementById("progressBar").style.width = "100%"; 
               document.getElementById("percentComplete").innerHTML = "Done!"; 
            } 
         } 
      } 
      else 
      { 
         alert(req.statusText); 
      } 
   } 
} 
</script> 
</head> 
<body> 
   <iframe id="uploadFrameID" name="uploadFrame" height="0" width="0" frameborder="0" scrolling="yes"></iframe>              
   <form id="myForm" enctype="multipart/form-data" method="post" target="uploadFrame" 
      action="http://stip-nb.ad.inside.mts.ru:8080/AJAXFileUpload/FileUploadServlet" onsubmit="ajaxFunction()"> 
       <input type="file" name="txtFile" id="txtFile" /><br /> 
       <input type="submit" id="submitID" name="submit" value="Upload" /> 
   </form> 
    
   <!-- Add hidden DIVs for updating and the progress bar (just a table) below the form --> 
   <div id="initializing" style="visibility: hidden; position: absolute; top: 100px;"> 
      <table width="100%" style="border: 1px; background-color: black;"> 
         <tr> 
            <td> 
               <table width="100%" style="border: 1px; background-color: black; color: white;"> 
                  <tr> 
                     <td align="center"> 
                        <b>Initializing Upload...</b> 
                     </td> 
                  </tr> 
               </table> 
            </td> 
         </tr> 
      </table> 
   </div> 
    
   <div id="progressBarTable" style="visibility: hidden; position: absolute; top: 100px;"> 
      <table width="100%" style="border: 1px; background-color: black; color: white;"> 
         <tr> 
            <td> 
               <table id="progressBar" width="0px" 
                  style="border: 1px; width: 0px; background-color: blue;"> 
                  <tr> 
                     <td> </td> 
                  </tr> 
               </table> 
            </td> 
         </tr> 
      </table> 
      <table width="100%" style="background-color: white; color: black;"> 
         <tr> 
            <td align="center" nowrap="nowrap"> 
               <span id="bytesRead" style="font-weight: bold;"> </span> 
            </td> 
         </tr> 
      </table>       
   </div> 
 
   <div id="percentCompleteTable" align="center" 
      style="visibility: hidden; position: absolute; top: 100px;"> 
      <table width="100%" style="border: 1px;"> 
         <tr> 
            <td> 
               <table width="100%" style="border: 1px;"> 
                  <tr> 
                     <td align="center" nowrap="nowrap"> 
                         <span id="percentComplete" style="color: white; font-weight: bold;"> </span> 
                     </td> 
                  </tr> 
               </table> 
            </td> 
         </tr> 
      </table> 
      </div> 
</body> 
</html>
 
this is a servlet code:
package stip.fileupload; 
 
import javax.servlet.Servlet; 
import javax.servlet.http.HttpServlet; 
import java.io.File; 
import java.io.IOException; 
import java.io.PrintWriter; 
import java.util.Iterator; 
import java.util.List; 
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import javax.servlet.http.HttpSession; 
import org.apache.commons.fileupload.FileItem; 
import org.apache.commons.fileupload.FileItemFactory; 
import org.apache.commons.fileupload.FileUploadException; 
import org.apache.commons.fileupload.disk.DiskFileItemFactory; 
import org.apache.commons.fileupload.servlet.ServletFileUpload; 
 
/** 
 * This is a File Upload Servlet that is used with AJAX 
 * to monitor the progress of the uploaded file. It will 
 * return an XML object containing the meta information 
 * as well as the percent complete. 
 * 
 * @author Frank T. Rios 
 * 
 * Initial Creation Date: 6/24/2007 
 */ 
public class FileUploadServlet 
        extends HttpServlet 
        implements Servlet { 
 
    private static final long serialVersionUID = 2740693677625051632L; 
 
    public FileUploadServlet() { 
        super(); 
    } 
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException { 
        PrintWriter out = response.getWriter(); 
        HttpSession session = request.getSession(); 
        FileUploadListener listener = null; 
        StringBuffer buffy = new StringBuffer(); 
        long bytesRead = 0, 
                contentLength = 0; 
 
        // Make sure the session has started 
        if (session == null) { 
            return; 
        } else if (session != null) { 
            // Check to see if we've created the listener object yet 
            listener = (FileUploadListener) session.getAttribute("LISTENER"); 
 
            if (listener == null) { 
                return; 
            } else { 
                // Get the meta information 
                bytesRead = listener.getBytesRead(); 
                contentLength = listener.getContentLength(); 
            } 
        } 
 
        /* 
         * XML Response Code 
         */ 
        response.setContentType("text/xml"); 
 
        buffy.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"); 
        buffy.append("<response>\n"); 
        buffy.append("\t<bytes_read>" + bytesRead + "</bytes_read>\n"); 
        buffy.append("\t<content_length>" + contentLength + "</content_length>\n"); 
 
        // Check to see if we're done 
        if (bytesRead == contentLength) { 
            buffy.append("\t<finished />\n"); 
 
            // No reason to keep listener in session since we're done 
            session.setAttribute("LISTENER", null); 
        } else { 
            // Calculate the percent complete 
            long percentComplete = ((100 * bytesRead) / contentLength); 
 
            buffy.append("\t<percent_complete>" + percentComplete + "</percent_complete>\n"); 
        } 
 
        buffy.append("</response>\n"); 
 
        out.println(buffy.toString()); 
        out.flush(); 
        out.close(); 
    } 
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException { 
        // create file upload factory and upload servlet 
        FileItemFactory factory = new DiskFileItemFactory(); 
        ServletFileUpload upload = new ServletFileUpload(factory); 
 
        // set file upload progress listener 
        FileUploadListener listener = new FileUploadListener(); 
 
        HttpSession session = request.getSession(); 
 
        session.setAttribute("LISTENER", listener); 
 
        // upload servlet allows to set upload listener 
        upload.setProgressListener(listener); 
 
        List uploadedItems = null; 
        FileItem fileItem = null; 
        String filePath = "d:\\temp";   // Path to store file on local system 
 
        try { 
            // iterate over all uploaded files 
            uploadedItems = upload.parseRequest(request); 
 
            Iterator i = uploadedItems.iterator(); 
 
            while (i.hasNext()) { 
                fileItem = (FileItem) i.next(); 
 
                if (fileItem.isFormField() == false) { 
                    if (fileItem.getSize() > 0) { 
                        File uploadedFile = null; 
                        String myFullFileName = fileItem.getName(), 
                                myFileName = "", 
                                slashType = (myFullFileName.lastIndexOf("\\") > 0) ? "\\" : "/"; // Windows or UNIX 
                        int startIndex = myFullFileName.lastIndexOf(slashType); 
 
                        // Ignore the path and get the filename 
                        myFileName = myFullFileName.substring(startIndex + 1, myFullFileName.length()); 
 
                        // Create new File object 
                        uploadedFile = new File(filePath, myFileName); 
 
                        // Write the uploaded file to the system 
                        fileItem.write(uploadedFile); 
                    } 
                } 
            } 
        } catch (FileUploadException e) { 
            e.printStackTrace(); 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
    } 
} 
 
and this is a listener:
package stip.fileupload; 
 
import org.apache.commons.fileupload.ProgressListener; 
 
/** 
 * This is a File Upload Listener that is used by Apache 
 * Commons File Upload to monitor the progress of the 
 * uploaded file. 
 * 
 * @author Frank T. Rios 
 * 
 * Initial Creation Date: 6/24/2007 
 */ 
public class FileUploadListener 
   implements ProgressListener 
{ 
    private volatile long 
       bytesRead = 0L, 
       contentLength = 0L, 
       item = 0L;    
    
    public FileUploadListener() 
    { 
       super(); 
    } 
    
    public void update(long aBytesRead, long aContentLength, int anItem) 
    { 
        bytesRead = aBytesRead; 
        contentLength = aContentLength; 
        item = anItem; 
    } 
    
    public long getBytesRead() 
    { 
        return bytesRead; 
    } 
    
    public long getContentLength() 
    { 
        return contentLength; 
    } 
    
    public long getItem() 
    { 
        return item; 
    } 
}
 
Keywords: AJAX, common fileupload progressba…
 
Loading Advertisement...
 
[+][-]01.12.2008 at 07:52AM PST, ID: 20644236

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 7-day free trial to view this Author Comment or ask the Experts your question.

 
[+][-]01.12.2008 at 08:40AM PST, ID: 20644453

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 7-day free trial to view this Author Comment or ask the Experts your question.

 
[+][-]01.12.2008 at 10:07AM PST, ID: 20644744

View this solution now by starting your 7-day free trial. Setting up your free trial is quick, easy, and secure. We will return you to this solution, unlocked, when you're done.

 

About this solution

Zones: WebApplications, JavaScript, Java Servlets
Tags: JSP, Java, AJAX, JavaScript, IE 7.0, Firefox
Sign Up Now!
Solution Provided By: hielo
Participating Experts: 1
Solution Grade: A
 
 
 
Loading Advertisement...
20080716-EE-VQP-32 / EE_QW_2_20070628