title: How post data from servlet to Javascript or how post uploaded bytes to HTML from servlet
body: <p>I want to upload files to server, but I don't understand:How post data from servlet to javascipt or how post uploaded bytes to html from servlet. Class, who upload file is UploadFileServlet, class who out in consol-UploadStream and form-uploadFile.html. UploadStream print data to consol, but I want to redirect this data to html-form and print. </p>
  
  <p><strong>UploadStream</strong></p>
  
  <pre><code>public static class UploadStream extends FilterOutputStream {
  
      final ProgressListener listener;
      private long transferred;
      public long bytes;
  
      public UploadStream(final OutputStream out, final ProgressListener listener) {
          super(out);
          this.listener = listener;
          this.transferred = 0;
      }
  
      public void write(byte[] b, int off, int len) throws IOException {
          out.write(b, off, len);
          bytes = this.transferred += len;
          System.out.println(this.transferred / 1024 + " KB");
      }
  
      public void write(int b) throws IOException {
          out.write(b);
          this.transferred++;
      }
  
      public void getBytes(HttpServletRequest request) throws ServletException, IOException {
          request.setAttribute("bytes", bytes);            
      }
  }
  </code></pre>
  
  <p><strong>UploadFileServlet</strong></p>
  
  <pre><code>public class UploadFileServlet extends HttpServlet {
      private boolean isMultipart;    
      //Maximum file size, 2gb
      private final int maxFileSize = 1024 * 1024 * 2000;
      //Maximum memory size, 3gb
      private final int maxMemSize = 1024 * 1024 * 3000;
      private File fileToSave;
  
      /**
       * Processes requests for both HTTP &lt;code&gt;GET&lt;/code&gt; and &lt;code&gt;POST&lt;/code&gt;
       * methods.
       *
       * @param request servlet request
       * @param response servlet response
       * @throws ServletException if a servlet-specific error occurs
       * @throws IOException if an I/O error occurs
       */
      protected void processRequest(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException {
  
      }
  
      // &lt;editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."&gt;
      /**
       * Handles the HTTP &lt;code&gt;GET&lt;/code&gt; method.
       *
       * @param request servlet request
       * @param response servlet response
       * @throws ServletException if a servlet-specific error occurs
       * @throws IOException if an I/O error occurs
       */
      @Override
      protected void doGet(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException  {
          processRequest(request, response);
      }
  
      /**
       * Handles the HTTP &lt;code&gt;POST&lt;/code&gt; method.
       *
       * @param request servlet request
       * @param response servlet response
       * @throws ServletException if a servlet-specific error occurs
       * @throws IOException if an I/O error occurs
       */
      @Override
      protected void doPost(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException {
          processRequest(request, response);        
          response.setContentType("text/html;charset=UTF-8");
          isMultipart = ServletFileUpload.isMultipartContent(request);        
          java.io.PrintWriter out = response.getWriter();
          if (!isMultipart) {
              out.println("&lt;h1&gt;No file uploaded&lt;/h1&gt;");
              return;
          }
          DiskFileItemFactory factory = new DiskFileItemFactory();
          // maximum size that will be stored in memory
          factory.setSizeThreshold(maxMemSize);        
          // Create a new file upload handler
          ServletFileUpload upload = new ServletFileUpload(factory);
          // maximum file size to be uploaded.
          upload.setSizeMax(maxFileSize);
  
          try {
              // Parse the request to get file items.
              List fileItems = upload.parseRequest(request);
              // Process the uploaded file items
              Iterator i = fileItems.iterator();
              while (i.hasNext()) {
                  FileItem fi = (FileItem) i.next();
                  if (!fi.isFormField()) {
                      // Get the uploaded file parameters
                      String fieldName = fi.getFieldName();
                      String fileName = fi.getName();
                      String contentType = fi.getContentType();
                      boolean isInMemory = fi.isInMemory();
                      long sizeInBytes = fi.getSize();
                      // Write the file
                      if (fileName.lastIndexOf("\\") &gt;= 0) {
                          fileToSave = new File(this
                                  + fileName.substring(fileName.lastIndexOf("\\")));
                      } else {
                          fileToSave = new File(this
                                  + fileName.substring(fileName.lastIndexOf("\\") + 1));
                      }
                      fi.write(fileToSave);
                  }
              }
          } catch (Exception ex) {
              out.println(ex.getMessage());
          }
          /* TODO output your page here. You may use following sample code. */        
          out.println("Image uploaded!");    
          File file = new File(fileToSave.getAbsoluteFile().toString());        
          String date = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new Date (System.currentTimeMillis()));       
          HttpParams params = new BasicHttpParams();
          params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, true);
          HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
          HttpClient client = new DefaultHttpClient(params);
          HttpPost post = new HttpPost(getUrl()+"upload.php");        
          MultipartEntity reqEntity = new MultipartEntity(){
          ProgressListener listener; 
                  public void writeTo(final OutputStream outstream) throws IOException {
                      super.writeTo(new UploadStream(outstream,listener));            
                  }
              };
          FileInputStream fis  = new FileInputStream(file);
          autorization(reqEntity,"upload");
          reqEntity.addPart("title", new StringBody(date));
          reqEntity.addPart("media", new InputStreamBody(fis, file.toString()));
          post.setEntity(reqEntity);
          HttpResponse httpResponse = client.execute(post);
          HttpEntity resEntity = httpResponse.getEntity();
          InputStream inputStream = resEntity.getContent();
          String resultString = ProjectLibrary.convertStreamToString(inputStream);
          //request.setAttribute("bytes", "");
              String url = "/WEB-INF/jsp/resultsUploadFile.jsp";
              request.getRequestDispatcher(url).forward(request, response);
          file.delete();
      }    
      /**
       * Returns a short description of the servlet.
       *
       * @return a String containing servlet description
       */
      @Override
      public String getServletInfo() {
          return "Short description";
      }// &lt;/editor-fold&gt;
  }
  </code></pre>
  
  <p>The HTML:</p>
  
  <pre><code>&lt;!DOCTYPE HTML&gt;
  &lt;html&gt;
      &lt;head&gt;
          &lt;title&gt;Multiple file uploader&lt;/title&gt;
          &lt;script&gt;
              var totalFileLength, totalUploaded, fileCount, filesUploaded;
  
              function debug(s) {
                  var debug = document.getElementById('debug');
                  if (debug) {
                      debug.innerHTML = debug.innerHTML + '&lt;br/&gt;' + s;
                  }
              }
  
              function onUploadComplete(e) {
                  totalUploaded += document.getElementById('files').
                          files[filesUploaded].size;
                  filesUploaded++;
                  debug('complete ' + filesUploaded + " of " + fileCount);
                  debug('totalUploaded: ' + totalUploaded);
                  if (filesUploaded &lt; fileCount) {
                      uploadNext();
                  } else {
                      alert('Finished uploading file(s)');
                  }
              }
  
              function onFileSelect(e) {
                  var files = e.target.files; // FileList object
                  var output = [];
                  fileCount = files.length;
                  totalFileLength = 0;
                  for (var i = 0; i &lt; fileCount; i++) {
                      var file = files[i];
                      output.push(file.name, ' (',
                              file.size, ' bytes, ',
                              file.lastModifiedDate.toLocaleDateString(), ')'
                              );
                      output.push('&lt;br/&gt;');
                      debug('add ' + file.size);
                      totalFileLength += file.size;
                  }
                  document.getElementById('selectedFiles').innerHTML =
                          output.join('');
                  debug('totalFileLength:' + totalFileLength);
              }
  
              function onUploadProgress(e) {
                  if (e.lengthComputable) {
                      var percentComplete = parseInt(
                              (e.loaded + totalUploaded) * 100
                              / totalFileLength);
                      var bar = document.getElementById('bar');
                      bar.style.width = percentComplete + '%';
                      bar.innerHTML = percentComplete + ' % complete';
                  } else {
                      debug('unable to compute');
                  }
              }
  
              function onUploadFailed(e) {
                  alert("Error uploading file:" + e);
              }
  
              function uploadNext() {
                  var xhr = new XMLHttpRequest();
                  var fd = new FormData();
                  var file = document.getElementById('files').files[filesUploaded];
                  fd.append('media', file);
                  xhr.upload.addEventListener("progress", onUploadProgress, false);
                  xhr.addEventListener("load", onUploadComplete, false);
                  xhr.addEventListener("error", onUploadFailed, false);
                  debug('uploading ' + file.name);
                  xhr.open('POST', 'UploadFileServlet', true);
                  xhr.send(fd);
              }
  
              function startUpload() {
                  totalUploaded = filesUploaded = 0;
                  uploadNext();
              }
              window.onload = function () {
                  document.getElementById('files').addEventListener(
                          'change', onFileSelect, false);
                  document.getElementById('uploadButton').
                          addEventListener('click', startUpload, false);
              }
  
          &lt;/script&gt;        
      &lt;/head&gt;
      &lt;body&gt;        
          &lt;h1&gt;Multiple file uploader&lt;/h1&gt;
          &lt;div id='progressBar' style='height:20px;border:2px solid green'&gt;
              &lt;div id='bar' 
                   style='height:100%;background:#33dd33;width:0%'&gt;
              &lt;/div&gt;
          &lt;/div&gt;
          &lt;form id='form1' action="UploadFileServlet" 
                enctype="multipart/form-data" method="post"&gt;    
              &lt;input type="file" id="files" multiple/&gt;
              &lt;br/&gt;
              &lt;output id="selectedFiles"&gt;&lt;/output&gt;
              &lt;input id="uploadButton" type="submit" value="Upload"/&gt;
          &lt;/form&gt;
          &lt;div id='debug' 
               style='height:100px;border:2px solid green;overflow:auto'&gt;
          &lt;/div&gt;
      &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>