Your SlideShare is downloading. ×
Dojo File Upload ProgressBar - Java Servlet
Dojo File Upload ProgressBar - Java Servlet
Dojo File Upload ProgressBar - Java Servlet
Dojo File Upload ProgressBar - Java Servlet
Dojo File Upload ProgressBar - Java Servlet
Dojo File Upload ProgressBar - Java Servlet
Dojo File Upload ProgressBar - Java Servlet
Dojo File Upload ProgressBar - Java Servlet
Dojo File Upload ProgressBar - Java Servlet
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Dojo File Upload ProgressBar - Java Servlet

3,096

Published on

Descarge el PDF y el codigo Fuente desde http://www.lulu.com/content/multimedia/dojo-file-upload---java-servlet/7996128 …

Descarge el PDF y el codigo Fuente desde http://www.lulu.com/content/multimedia/dojo-file-upload---java-servlet/7996128

Demo como subir Archivos usando Widgets de Dojo Toolkit(dijit.ProgressBar, dojo.io.iframe,dijit.form.Button,dojo.xhrGet, etc.),Java (Servlet, Struts). El monitoreo de progreso de la subida del archivo usando org.apache.commons.fileupload.ProgressListener

Published in: Technology, Education
2 Comments
13 Likes
Statistics
Notes
  • Soy un aprendiz de Dojo


    <b>[Comment posted from</b> http://blog.gwthispano.org/2009/07/dojo-file-upload-progress-bar.html]
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Descarge el PDF y el codigo Fuente desde http://www.lulu.com/content/multimedia/dojo-file-upload---java-servlet/7996128
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total Views
3,096
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
1
Comments
2
Likes
13
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Dojo File Upload Progress Bar Widget Upload.jsp contiene un form "multipart/form-data" para subir archives al sevlet "test" indicado en el Web.xml. Ademas de tener un barra de progreso que mide el porcentaje de subida usando org.apache.commons.fileupload.ProgressListener la sincronizaci&#xF3;n de la subida de archivo se realiza con dojo.xhrGet llamando el sevlet progress. &lt;%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"&gt; &lt;title&gt;SuperLink&lt;/title&gt; &lt;style type="text/css"&gt; @import "js/dojotoolkit/dijit/themes/tundra/tundra.css"; @import "js/dojotoolkit/dijit/themes/nihilo/soria.css"; @import "js/dojotoolkit/dijit/themes/dijit.css"; @import "js/dojotoolkit/dijit/themes/nihilo/nihilo.css"; @import "js/dojotoolkit/dojo/resources/dojo.css" &lt;/style&gt; &lt;script type="text/javascript" src="js/dojotoolkit/dojo/dojo.js" djConfig="parseOnLoad: true"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/jsonrpc.js"&gt;&lt;/script&gt; &lt;/script&gt; &lt;script type="text/javascript"&gt; dojo.require("dijit.ProgressBar"); dojo.require("dijit.form.ComboBox"); dojo.require("dijit.form.DateTextBox"); dojo.require("dojo.parser"); dojo.require("dijit.form.FilteringSelect"); dojo.require("dijit.form.Button"); dojo.require("dijit.form.ComboBox"); dojo.require("dijit.layout.SplitContainer"); dojo.require("dijit.layout.ContentPane"); dojo.require("dijit.form.ComboBox"); dojo.require("dojo.data.ItemFileReadStore"); dojo.require("dijit.form.TextBox"); dojo.require("dojo.io.iframe"); dojo.require("dijit.Tooltip"); dojo.require("dijit.layout.TabContainer"); dojo.require("dijit.layout.ContentPane"); dojo.addOnLoad(function(){ dijit.byId('downloadProgress').domNode.style.display = "none"; var StoreMes = new dojo.data.ItemFileReadStore({url: "http://localhost:9080/SidAjax/util/mes.json"}); var selectMes = new dijit.form.ComboBox({id: "mes", name: "mes", value: "Enero", store: StoreMes, searchAttr: "name"}, "mes"); var StoreAnios = new dojo.data.ItemFileReadStore({url: "http://localhost:9080/SidAjax/util/anios.json"}); var selectAnios = new dijit.form.ComboBox({id: "anios", name: "anio", value: "2009", store: StoreAnios, searchAttr: "name"}, "anios"); var StorePais = new dojo.data.ItemFileReadStore({url: "http://localhost:9080/SidAjax/util/paises.json"}); var selectPais = new dijit.form.ComboBox({id: "pais", name: "pais", value: "Peru", store: StorePais, searchAttr: "name"}, "pais"); var StoreCats = new dojo.data.ItemFileReadStore({url: "http://localhost:9080/SidAjax/util/cats.json"}); var selectCats = new dijit.form.ComboBox({id: "cats", name: "cats", value: "Desplazamiento", store: StoreCats, searchAttr: "name"}, "cats"); }); var load=0; var upload=false; function doProgress() { dijit.byId('downloadProgress').domNode.style.display = "block"; //dijit.byId('submitButton').domNode.style.display = "none"; jsProgress.update({ maximum: 100, progress: 0 }); doProgressLoop(); } function doProgressLoop() { if (load &lt; 100 ) {
  • 2. getProgress(); setTimeout("jsProgress.update({ progress: " + load + " })", (load+1)*50 + Math.floor(Math.random()*100)); setTimeout("doProgressLoop()", 700); if(upload){ killProgress(); load=100; dijit.byId("submitButton").enabled='true'; } }else{ jsProgress.update({ progress: 100 }); dijit.byId('downloadProgress').domNode.style.display = "none"; dijit.byId("submitButton").disabled='false'; //dijit.byId('submitButton').domNode.style.display = "block"; } } function getProgress() { if(load&lt;100){ dojo.xhrGet({url: 'progress', handleAs: "text", load: function (data) { if(data==100){ load=100; }else if(data&lt;100){ load=data; } //dojo.byId('response').innerHTML = load; }, error: function (data) { //dojo.byId('response').innerHTML = "Error retrieving progress"+data; } }); } } function killProgress() { if(load&lt;100){ dojo.xhrGet({url: 'killprogress', handleAs: "text", load: function (data) { //dojo.byId('response').innerHTML = "killed progres"; }, error: function (data) { //dojo.byId('response').innerHTML = "Error retrieving progress"+data; } }); } } function sendForm(){ var button = dijit.byId("submitButton"); dojo.connect(button, "onClick", function(event){ button.disabled='true'; event.preventDefault(); event.stopPropagation(); var xhrArgs = { form: dojo.byId("myform"), handleAs: "html", method: 'POST', contentType: "multipart/form-data", load: function(data){ //dojo.byId("response").innerHTML = "Archivo Subido OK."+ data; //dijit.byId("submitButton").disabled='false'; upload=true; }, error: function(error){ //dojo.byId("response").innerHTML = "Error al subir archivo."; } } var deferred = dojo.io.iframe.send(xhrArgs); doProgress(); dojo.byId("response").innerHTML = "fue enviado..." }); } dojo.addOnLoad(sendForm); &lt;/script&gt; &lt;/head&gt; &lt;body class="tundra"&gt; &lt;div style="height: 105px;"&gt; &lt;div dojoType="dijit.layout.TabContainer" style="width: 100%;" doLayout="false"&gt; &lt;div dojoType="dijit.layout.ContentPane" title="Zona SuperLink" selected="true"&gt; &lt;blockquote&gt; &lt;div&gt; &lt;form name="form1" id="myform" action="test" enctype="multipart/form-data"&gt; &lt;input id="mes" style="width: 120px"&gt; &lt;input id="anios" style="width: 120px;"&gt; &lt;input id="pais" style="width: 120px;"&gt; &lt;br&gt; &lt;input id="cats" style="width: 120px;"&gt; &lt;input id="q01" type="text" name="nombre" style="width: 170px;" dojoType="dijit.form.ValidationTextBox" required="true" invalidMessage="Ingresar nombre del Archivo!"/&gt; &lt;input type="file" size="50" name="file1"&gt; &lt;button type="submit" dojoType="dijit.form.Button" id="submitButton"&gt;Cargar&lt;/button&gt; &lt;/form&gt; &lt;div class="tundra"&gt;&lt;div dojoType="dijit.ProgressBar" style="width: 300px" jsId="jsProgress" id="downloadProgress"&gt; &lt;/div&gt;&lt;/div&gt; &lt;/div&gt; &lt;/blockquote&gt; &lt;div dojoType="dijit.Tooltip" connectId="q01" position="['above']"&gt; Ingresar nombre del Archivo &lt;/div&gt; &lt;!-- &lt;br&gt; &lt;b&gt;Result&lt;/b&gt; &lt;div id="response"&gt;&lt;/div&gt;--&gt; &lt;/div&gt; &lt;div dojoType="dijit.layout.ContentPane" title="Zona Descarga"&gt; aaaaaaaaaaaaaaaaaaa &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; dddddddddddddddddd &lt;/div&gt;
  • 3. &lt;/div&gt; &lt;!-- end of the div --&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; Servlet TestServlet: Encargado de recibir los archives enviados desde el upload.jsp. adem&#xE1;s de crear una sesi&#xF3;n de donde setea TestProgressListener que se encarga de monitorear el File Upload. package test; import java.io.IOException; import java.io.PrintWriter; import java.util.Iterator; import java.util.List; import javax.servlet.http.HttpServlet; 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; public class TestServlet extends HttpServlet { private static final long serialVersionUID = 1L; // public static final long MAX_UPLOAD_IN_MEGS = 50; public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); boolean isMultipartContent = ServletFileUpload.isMultipartContent(request); if (!isMultipartContent) { System.out.println("You are not trying to upload "); return; } FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); //upload.setSizeMax(MAX_UPLOAD_IN_MEGS * 1024 * 1024); TestProgressListener testProgressListener = new TestProgressListener(); upload.setProgressListener(testProgressListener); HttpSession session = request.getSession(); session.setAttribute("testProgressListener", testProgressListener);
  • 4. try { System.out.println("Inicio de Carga"); List fields = upload.parseRequest(request); Iterator it = fields.iterator(); if (!it.hasNext()) { System.out.println("No fields found " + fields.size() ); return; } while (it.hasNext()) { FileItem fileItem = (FileItem)it.next(); boolean isFormField = fileItem.isFormField(); if (isFormField) { System.out.println("FieldName :"+fileItem.getFieldName()+" Valor:"+fileItem.getString()); } else { System.out.println("FieldName :"+fileItem.getFieldName()+" name "+fileItem.getName() +" "+fileItem.getContentType() +" "+fileItem.getSize() +" Valor:"+fileItem.getSize() + " archivo "+fileItem.toString()); } } //session.removeAttribute("testProgressListener"); out.print("Archivo subido"); System.out.println("Carga Finalizada"); } catch (FileUploadException e) { System.out.println("e "+ e.getMessage()); e.printStackTrace(); } } }
  • 5. TestProgressListener : Clase de Monitoreo que permite medir el progreso de la sibida de archivos package test; import org.apache.commons.fileupload.ProgressListener; public class TestProgressListener implements ProgressListener { private long num100Ks = 0; private long theBytesRead = 0; private long theContentLength = -1; private int whichItem = 0; private int percentDone = 0; private boolean contentLengthKnown = false; public void update(long bytesRead, long contentLength, int items) { if (contentLength &gt; -1) { contentLengthKnown = true; } theBytesRead = bytesRead; theContentLength = contentLength; whichItem = items; long nowNum100Ks = bytesRead / 100000; // Only run this code once every 100K if (nowNum100Ks &gt; num100Ks) { num100Ks = nowNum100Ks; if (contentLengthKnown) { percentDone = (int) Math.round(100.00 * bytesRead / contentLength); } //System.out.println("getMessage() : "+getMessage()); } } public String getMessage() { if (theContentLength == -1) { return "" + theBytesRead + " of Unknown-Total bytes have been read."; } else { return "" + theBytesRead + " de " + theContentLength + " bytes se han subido(" + percentDone + "% )."; } } public long getNum100Ks() { return num100Ks; } public void setNum100Ks(long num100Ks) { this.num100Ks = num100Ks; }
  • 6. public long getTheBytesRead() { return theBytesRead; } public void setTheBytesRead(long theBytesRead) { this.theBytesRead = theBytesRead; } public long getTheContentLength() { return theContentLength; } public void setTheContentLength(long theContentLength) { this.theContentLength = theContentLength; } public int getWhichItem() { return whichItem; } public void setWhichItem(int whichItem) { this.whichItem = whichItem; } public int getPercentDone() { return percentDone; } public void setPercentDone(int percentDone) { this.percentDone = percentDone; } public boolean isContentLengthKnown() { return contentLengthKnown; } public void setContentLengthKnown(boolean contentLengthKnown) { this.contentLengthKnown = contentLengthKnown; } }
  • 7. ProgressServlet: clase que obtiene TestProgressListener de una sesi&#xF3;n creada en el ServletTest, este servlet proporciona el estado de progreso de la subida de archivo package test; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class ProgressServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(true); if (session == null) { out.println("Sorry, session is null"); // just to be safe return; } TestProgressListener testProgressListener = (TestProgressListener) session.getAttribute("testProgressListener"); if (testProgressListener == null) { out.println("Progress listener is null"); return; } out.println(testProgressListener.getPercentDone()); } }
  • 8. KillProgressServlet: Clase que se usa para eliminar la session que guarda el estado de la subida de archivos, esta clase es invocada cuando el progreso de la subida de archivo llega al 100%. package test; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class KillProgressServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(true); TestProgressListener testProgressListener = (TestProgressListener) session.getAttribute("testProgressListener"); if (testProgressListener != null) { session.removeAttribute("testProgressListener"); System.out.println("remove session"); return; } } }
  • 9. &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"&gt; &lt;display-name&gt; SidAjax&lt;/display-name&gt; &lt;servlet&gt; &lt;servlet-name&gt;action&lt;/servlet-name&gt; &lt;servlet-class&gt; org.apache.struts.action.ActionServlet&lt;/servlet-class&gt; &lt;init-param&gt; &lt;param-name&gt;config&lt;/param-name&gt; &lt;param-value&gt;/WEB-INF/struts-config.xml&lt;/param-value&gt; &lt;/init-param&gt; &lt;init-param&gt; &lt;param-name&gt;debug&lt;/param-name&gt; &lt;param-value&gt;2&lt;/param-value&gt; &lt;/init-param&gt; &lt;init-param&gt; &lt;param-name&gt;detail&lt;/param-name&gt; &lt;param-value&gt;2&lt;/param-value&gt; &lt;/init-param&gt; &lt;init-param&gt; &lt;param-name&gt;validate&lt;/param-name&gt; &lt;param-value&gt;true&lt;/param-value&gt; &lt;/init-param&gt; &lt;load-on-startup&gt;2&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet&gt; &lt;description&gt; &lt;/description&gt; &lt;display-name&gt; com.metaparadigm.jsonrpc.JSONRPCServlet&lt;/display-name&gt; &lt;servlet-name&gt;com.metaparadigm.jsonrpc.JSONRPCServlet&lt;/servlet-name&gt; &lt;servlet-class&gt; com.metaparadigm.jsonrpc.JSONRPCServlet&lt;/servlet-class&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;action&lt;/servlet-name&gt; &lt;url-pattern&gt;*.do&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;com.metaparadigm.jsonrpc.JSONRPCServlet&lt;/servlet-name&gt; &lt;url-pattern&gt;/JSON-RPC&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;servlet&gt; &lt;servlet-name&gt;ImagenServlet&lt;/servlet-name&gt; &lt;servlet-class&gt;sidajax.servlet.ImagenServlet&lt;/servlet-class&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;ImagenServlet&lt;/servlet-name&gt; &lt;url-pattern&gt;/ImagenServlet&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;servlet&gt; &lt;servlet-name&gt;TestServlet&lt;/servlet-name&gt; &lt;servlet-class&gt;test.TestServlet&lt;/servlet-class&gt; &lt;/servlet&gt; &lt;servlet&gt; &lt;servlet-name&gt;ProgressServlet&lt;/servlet-name&gt; &lt;servlet-class&gt;test.ProgressServlet&lt;/servlet-class&gt; &lt;/servlet&gt; &lt;servlet&gt; &lt;servlet-name&gt;KillProgressServlet&lt;/servlet-name&gt; &lt;servlet-class&gt;test.KillProgressServlet&lt;/servlet-class&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;TestServlet&lt;/servlet-name&gt; &lt;url-pattern&gt;/test&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;ProgressServlet&lt;/servlet-name&gt; &lt;url-pattern&gt;/progress&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;KillProgressServlet&lt;/servlet-name&gt; &lt;url-pattern&gt;/killprogress&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;welcome-file-list&gt; &lt;welcome-file&gt;index.html&lt;/welcome-file&gt; &lt;welcome-file&gt;index.htm&lt;/welcome-file&gt; &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt; &lt;welcome-file&gt;default.html&lt;/welcome-file&gt; &lt;welcome-file&gt;default.htm&lt;/welcome-file&gt; &lt;welcome-file&gt;default.jsp&lt;/welcome-file&gt; &lt;/welcome-file-list&gt; &lt;jsp-config&gt; &lt;taglib&gt; &lt;taglib-uri&gt;/WEB-INF/struts-bean.tld&lt;/taglib-uri&gt; &lt;taglib-location&gt;/WEB-INF/struts-bean.tld&lt;/taglib-location&gt; &lt;/taglib&gt; &lt;taglib&gt; &lt;taglib-uri&gt;/WEB-INF/struts-html.tld&lt;/taglib-uri&gt; &lt;taglib-location&gt;/WEB-INF/struts-html.tld&lt;/taglib-location&gt; &lt;/taglib&gt; &lt;taglib&gt; &lt;taglib-uri&gt;/WEB-INF/struts-logic.tld&lt;/taglib-uri&gt; &lt;taglib-location&gt;/WEB-INF/struts-logic.tld&lt;/taglib-location&gt; &lt;/taglib&gt; &lt;taglib&gt; &lt;taglib-uri&gt;/WEB-INF/struts-nested.tld&lt;/taglib-uri&gt; &lt;taglib-location&gt;/WEB-INF/struts-nested.tld&lt;/taglib-location&gt; &lt;/taglib&gt; &lt;taglib&gt; &lt;taglib-uri&gt;/WEB-INF/struts-template.tld&lt;/taglib-uri&gt; &lt;taglib-location&gt;/WEB-INF/struts-template.tld&lt;/taglib-location&gt; &lt;/taglib&gt; &lt;taglib&gt; &lt;taglib-uri&gt;/WEB-INF/struts-tiles.tld&lt;/taglib-uri&gt; &lt;taglib-location&gt;/WEB-INF/struts-tiles.tld&lt;/taglib-location&gt; &lt;/taglib&gt; &lt;/jsp-config&gt; &lt;/web-app&gt;

×