Announcement Announcement Module
Collapse
No announcement yet.
Upload progress bar spring and prototype Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Upload progress bar spring and prototype

    Hi
    I'm using:
    • Spring 2.5.6
    • prototype.js
    • ajaxtags
    • tomcat 5.5.x and 6.0.x
    • jvm 1.6_11
    I'ld love to create a progress bar. I have found a very simple and nice sample that builds the progress bar by using commons-io and commons-fileupload
    I'ld love to integrate this sample in my Spring-MVC web app.
    In the sample there is a class and a servlet; the calss is this one:
    FileUploadListener.java
    Code:
    package test;
    import com.missiondata.fileupload.OutputStreamListener;
    public class FileUploadListener implements OutputStreamListener
    {
      private FileUploadStats fileUploadStats = new FileUploadStats();
    
      public FileUploadListener(long totalSize)
      {
        fileUploadStats.setTotalSize(totalSize);
      }
    
      public void start()
      {
        fileUploadStats.setCurrentStatus("start");
      }
    
      public void bytesRead(int byteCount)
      {
        fileUploadStats.incrementBytesRead(byteCount);
        fileUploadStats.setCurrentStatus("reading");
      }
    
      public void error(String s)
      {
        fileUploadStats.setCurrentStatus("error");
      }
    
      public void done()
      {
        fileUploadStats.setBytesRead(fileUploadStats.getTotalSize());
        fileUploadStats.setCurrentStatus("done");
      }
    
      public FileUploadStats getFileUploadStats()
      {
        return fileUploadStats;
      }
    
      public static class FileUploadStats
      {
        private long totalSize = 0;
        private long bytesRead = 0;
        private long startTime = System.currentTimeMillis();
        private String currentStatus = "none";
        public long getTotalSize()
        {
          return totalSize;
        }
    
        public void setTotalSize(long totalSize)
        {
          this.totalSize = totalSize;
        }
        public long getBytesRead()
        {
          return bytesRead;
        }
        public long getElapsedTimeInSeconds()
        {
          return (System.currentTimeMillis() - startTime) / 1000;
        }
        public String getCurrentStatus()
        {
          return currentStatus;
        }
        public void setCurrentStatus(String currentStatus)
        {
          this.currentStatus = currentStatus;
        }
        public void setBytesRead(long bytesRead)
        {
          this.bytesRead = bytesRead;
        }
        public void incrementBytesRead(int byteCount)
        {
          this.bytesRead += byteCount;
        }
      }
    }
    UploadServlet.java
    Code:
    package test;
    import org.apache.commons.fileupload.FileItemFactory;
    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import javax.servlet.ServletException;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.List;
    import java.util.Iterator;
    import com.missiondata.fileupload.MonitoredDiskFileItemFactory;
    public class UploadServlet extends HttpServlet
    {
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
      {
        doPost(request,response);
      }
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
      {
        HttpSession session = request.getSession();
        if("status".equals(request.getParameter("c")))
        {
          doStatus(session, response);
        }
        else
        {
          doFileUpload(session, request, response);
        }
      }
      private void doFileUpload(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException
      {
        try
        {
          FileUploadListener listener = new FileUploadListener(request.getContentLength());
          session.setAttribute("FILE_UPLOAD_STATS", listener.getFileUploadStats());
          FileItemFactory factory = new MonitoredDiskFileItemFactory(listener);
          ServletFileUpload upload = new ServletFileUpload(factory);
          List items = upload.parseRequest(request);
          boolean hasError = false;
          for (Iterator i = items.iterator(); i.hasNext();)
          {
            FileItem fileItem = (FileItem) i.next();
            if (!fileItem.isFormField())
            {
              fileItem.delete();
            }
          }
          if(!hasError)
          {
            sendCompleteResponse(response, null);
          }
          else
          {
            sendCompleteResponse(response, "Could not process uploaded file. Please see log for details.");
          }
        }
        catch (Exception e)
        {
          sendCompleteResponse(response, e.getMessage());
        }
      }
      private void doStatus(HttpSession session, HttpServletResponse response) throws IOException
      {
        // Make sure the status response is not cached by the browser
        response.addHeader("Expires", "0");
        response.addHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.addHeader("Pragma", "no-cache");
        FileUploadListener.FileUploadStats fileUploadStats = (FileUploadListener.FileUploadStats) session.getAttribute("FILE_UPLOAD_STATS");
        if(fileUploadStats != null)
        {
          long bytesProcessed = fileUploadStats.getBytesRead();
          long sizeTotal = fileUploadStats.getTotalSize();
          long percentComplete = (long)Math.floor(((double)bytesProcessed / (double)sizeTotal) * 100.0);
          long timeInSeconds = fileUploadStats.getElapsedTimeInSeconds();
          double uploadRate = bytesProcessed / (timeInSeconds + 0.00001);
          double estimatedRuntime = sizeTotal / (uploadRate + 0.00001);
          System.out.println("bytesProcessed--> "+bytesProcessed+" sizeTotal-->"+sizeTotal+" percentComplete-->"+percentComplete+" timeInSeconds-->"+timeInSeconds+" uploadRate-->"+uploadRate+" estimatedRuntime-->"+estimatedRuntime);
          response.getWriter().println("<b>Upload Status:</b><br/>");
          if(fileUploadStats.getBytesRead() != fileUploadStats.getTotalSize())
          {
            response.getWriter().println("<div class=\"prog-border\"><div class=\"prog-bar\" style=\"width: " + percentComplete + "%;\"></div></div>");
            response.getWriter().println("Uploaded: " + bytesProcessed + " out of " + sizeTotal + " bytes (" + percentComplete + "%) " + (long)Math.round(uploadRate / 1024) + " Kbs <br/>");
            response.getWriter().println("Runtime: " + formatTime(timeInSeconds) + " out of " + formatTime(estimatedRuntime) + " " + formatTime(estimatedRuntime - timeInSeconds) + " remaining <br/>");
          }
          else
          {
            response.getWriter().println("Uploaded: " + bytesProcessed + " out of " + sizeTotal + " bytes<br/>");
            response.getWriter().println("Complete.<br/>");
          }
        }
        if(fileUploadStats != null && fileUploadStats.getBytesRead() == fileUploadStats.getTotalSize())
        {
          response.getWriter().println("<b>Upload complete.</b>");
        }
      }
      private void sendCompleteResponse(HttpServletResponse response, String message) throws IOException
      {
        if(message == null)
        {
          response.getOutputStream().print("<html><head><script type='text/javascript'>function killUpdate() { window.parent.killUpdate(''); }</script></head><body onload='killUpdate()'></body></html>");
        }
        else
        {
          response.getOutputStream().print("<html><head><script type='text/javascript'>function killUpdate() { window.parent.killUpdate('" + message + "'); }</script></head><body onload='killUpdate()'></body></html>");
        }
      }
      private String formatTime(double timeInSeconds)
      {
        long seconds = (long)Math.floor(timeInSeconds);
        long minutes = (long)Math.floor(timeInSeconds / 60.0);
        long hours = (long)Math.floor(minutes / 60.0);
        if(hours != 0)
        {
          return hours + "hours " + (minutes % 60) + "minutes " + (seconds % 60) + "seconds";
        }
        else if(minutes % 60 != 0)
        {
          return (minutes % 60) + "minutes " + (seconds % 60) + "seconds";
        }
        else
        {
          return (seconds % 60) + " seconds";
        }
      }
    }
    uploadform.htm
    Code:
    <html>
    <head>
      <title>Test Upload</title>
     <script src="js/prototype.js" language="JavaScript" type="text/javascript"></script>
      <script type="text/javascript" language="JavaScript">
      var updater = null;
    
      function startStatusCheck()
      {
        $('submitButton').disabled = true;
    
        updater = new Ajax.PeriodicalUpdater(
                                    'status',
                                    'Upload',
                                    {asynchronous:true, frequency:1, method: 'get', parameters: 'c=status', onFailure: reportError});
        return true;
      }
      function killUpdate(message)
      {
        $('submitButton').disabled = false;
        updater.stop();
        if(message != '')
        {
          $('status').innerHTML = '<div class="error"><b>Error processing results: ' + message + '</b></div>';
        }
        else
        {
          new Ajax.Updater('status',
                         'Upload',
                         {asynchronous:true, method: 'get', parameters: 'c=status', onFailure: reportError});
        }
      }
      </script>
      <iframe id='target_upload' name='target_upload' src='' style='display: none'></iframe>
      <form enctype="multipart/form-data" name="form" method="post" action="Upload" onsubmit="return startStatusCheck();" target="target_upload">
        File to upload: <input id="importFile" name="importFile" type="file"> <br/>
        <input id="submitButton" type="submit"/>
      </form>
      <!-- This is the upload status area -->
      <div id="status"></div>
    By using this code i'm able to print in my html page the upload progress bar.
    How may introduce it in my Spring web application? The greatest problem is that i must write on the servlet response printwriter.
    How may i solve this thing?

    Thnx to all
    Angelo

  • #2
    Did you get Any Solution

    Hi
    Did you get any solution to the problem. I am facing the same problem of integrating it with my application. Though i have had success, if i try to run the piece of code from a separate standalone application. I am using the same technology as yours except for Spring MVC i am using struts2 and freemarker.

    Please provide me any solution, its urgent.

    Comment


    • #3
      Solution foud

      This is a solution that I try, use JQuery, Spring MVC, works great!

      http://abambenjamin.blogspot.mx/2012...ar-spring.html

      Comment

      Working...
      X