Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
Clear All
new posts

    Handling smartgwt upload without reloading

    Hi,

    I'm currently working on a smartgwt application that uses file upload with a .jsp
    on the server side and it works. The problem is that I would like to handle the upload without leaving the gwt application, I read that it could be possible to use rpc calls, DSRequest , DSResponse and rpc calls but I don't know how to do.

    #2
    Hi Pascal,

    The below thread might be useful

    http://forums.smartclient.com/showthread.php?t=3102

    Comment


      #3
      I would be great if one of you guys can add a sample of this to the smartgwt-extensions project. If you're interested, please let me know and I'll add you as a committer.

      Thanks,
      Sanjiv

      Comment


        #4
        Originally posted by Halabe
        Hi Pascal,

        The below thread might be useful

        http://forums.smartclient.com/showthread.php?t=3102
        Hi Halabe

        Thanks, in facts I saw this topic and the problem is that I would like some piece of minimal smartgwt code that would allow to make the upload with a .jsp without changing page.

        Comment


          #5
          Originally posted by sjivan
          I would be great if one of you guys can add a sample of this to the smartgwt-extensions project. If you're interested, please let me know and I'll add you as a committer.

          Thanks,
          Sanjiv
          Hi Sanjiv, sorry for the cross post. I'm interested(add a sample of this to the smartgwt-extensions project). How can we do that ?

          Comment


            #6
            An upload canvas

            Here is the upload canvas I use. I will put it on the page when I get a chance:
            Code:
            package edu.iastate.its.thinkspace.gwt.client.util.files;
            
            import java.util.ArrayList;
            import java.util.List;
            import java.util.Map;
            
            import com.google.gwt.user.client.ui.NamedFrame;
            import com.smartgwt.client.types.Alignment;
            import com.smartgwt.client.types.Encoding;
            import com.smartgwt.client.util.SC;
            import com.smartgwt.client.widgets.Button;
            import com.smartgwt.client.widgets.Canvas;
            import com.smartgwt.client.widgets.events.ClickEvent;
            import com.smartgwt.client.widgets.events.ClickHandler;
            import com.smartgwt.client.widgets.form.DynamicForm;
            import com.smartgwt.client.widgets.form.ValuesManager;
            import com.smartgwt.client.widgets.form.fields.CheckboxItem;
            import com.smartgwt.client.widgets.form.fields.FormItem;
            import com.smartgwt.client.widgets.form.fields.HiddenItem;
            import com.smartgwt.client.widgets.form.fields.UploadItem;
            import com.smartgwt.client.widgets.form.fields.events.ChangedEvent;
            import com.smartgwt.client.widgets.form.fields.events.ChangedHandler;
            import com.smartgwt.client.widgets.layout.VStack;
            
            public class Upload extends Canvas {
            	public static enum Mode {SIMPLE, COMPLEX};
            	public static final String TARGET="uploadTarget";
            
            	private DynamicForm uploadForm;
            	private UploadItem fileItem;
            	private UploadListener listener;
            	private List<HiddenItem> hiddenItems;
            	/**
            	 * 
            	 */
            	public Upload() {
            		this(null,Mode.SIMPLE);
            	}
            	
            	/**
            	 * @param args
            	 */
            	public Upload(Map<String,String> args,Mode mode) {
            		initComplete(this);
            		List<FormItem> items = new ArrayList<FormItem>();
            		if (args != null) {
            			hiddenItems = new ArrayList<HiddenItem>();
            			for(String key: args.keySet()) {
            				HiddenItem item = new HiddenItem(key);
            				item.setValue(args.get(key));
            				items.add(item);
            				hiddenItems.add(item);
            			};
            		}
            		ValuesManager vm = new ValuesManager();
            		uploadForm = new DynamicForm();
            		uploadForm.setValuesManager(vm);
            		uploadForm.setEncoding(Encoding.MULTIPART);
            		uploadForm.setTarget(TARGET);
            
            		fileItem = new UploadItem("file");
            		fileItem.setTitle("File");
            		fileItem.setWidth(300);
            		items.add(fileItem);
            		fileItem.addChangedHandler(new ChangedHandler() {
            			public void onChanged(ChangedEvent e) {
            				System.out.println("change");
            			}
            		});
            		Button uploadButton = new Button("Upload");
            		uploadButton.addClickHandler(new ClickHandler(){
            			public void onClick(ClickEvent e) {
            				Object obj = fileItem.getDisplayValue();
            				if (obj != null) {
            					uploadForm.submitForm();
            				} else
            					SC.say("Please select a file.");
            			}
            		});
            		VStack stack = new VStack();
            		stack.setWidth100();
            		stack.setMembersMargin(10);
            		stack.setDefaultLayoutAlign(Alignment.CENTER);
            
            		NamedFrame frame = new NamedFrame(TARGET);
            		frame.setWidth("1");
            		frame.setHeight("1");
            		frame.setVisible(false);
            
            		VStack mainLayout = new VStack();
            		mainLayout.setWidth(300);
            		mainLayout.setHeight(200);
            		
            		if (mode == Mode.COMPLEX) {		
            			CheckboxItem unzip = new CheckboxItem("unzip");
            			unzip.setDefaultValue(true);
            			unzip.setTitle("Unzip .zip file");
            			items.add(unzip);
            			CheckboxItem overwrite = new CheckboxItem("overwrite");
            			overwrite.setDefaultValue(false);
            			overwrite.setTitle("Overwrite existing file"); 
            			items.add(overwrite);
            			CheckboxItem convertpdf = new CheckboxItem("convertpdf");
            			convertpdf.setDefaultValue(true);
            			convertpdf.setTitle("Convert Word document to PDF"); 
            			items.add(convertpdf);
            			CheckboxItem streaming = new CheckboxItem("streaming");
            			streaming.setDefaultValue(true);
            			streaming.setTitle("Convert video file to streaming format(flv)"); 
            			items.add(streaming);
            			CheckboxItem thumbnail = new CheckboxItem("thumbnail");
            			thumbnail.setDefaultValue(true);
            			thumbnail.setTitle("Make thumbnail(48x48) from image");
            			items.add(thumbnail);
            		}
            		FormItem[] fitems = new FormItem[items.size()];
            		items.toArray(fitems);
            		uploadForm.setItems(fitems);
            		stack.addMember(uploadForm);
            		stack.addMember(uploadButton);
            		mainLayout.addMember(stack);
            		mainLayout.addMember(frame);
            		addChild(mainLayout);
            	}
            
            	public String getFile() {
            		Object obj = fileItem.getValue();
            		if (obj == null)
            			return null;
            		else
            			return obj.toString();
            	}
            
            	public void setHiddenItem(String name, String value) {
            		for (HiddenItem item: hiddenItems)
            			if (item.getName().equals(name)) {
            				item.setValue(value);
            				return;
            			}
            	}
            	
            	public void setAction(String url) {
            		uploadForm.setAction(url);
            	}
            	
            	public void setUploadListener(UploadListener listener) {
            		this.listener = listener;
            	}
            	
            	public void uploadComplete(String fileName) {
            		if (listener != null)
            			listener.uploadComplete(fileName);
            	}
            	
            	
            	private native void initComplete(Upload upload) /*-{
            	   $wnd.uploadComplete = function (fileName) {
            	       upload.@edu.iastate.its.thinkspace.gwt.client.util.files.Upload::uploadComplete(Ljava/lang/String;)(fileName);
            	   };
            	}-*/;
            }

            Comment


              #7
              Here is the upload servlet

              Code:
              The following is the code for my servlet.  See the if (isGWT) section:
              
              package edu.iastate.its.thinkspace.core.servlet;
              
              import java.io.File;
              import java.io.FileInputStream;
              import java.io.InputStream;
              import java.io.PrintWriter;
              import java.util.HashMap;
              
              import javax.servlet.http.HttpServlet;
              import javax.servlet.http.HttpServletRequest;
              import javax.servlet.http.HttpServletResponse;
              
              import org.apache.commons.fileupload.FileItemIterator;
              import org.apache.commons.fileupload.FileItemStream;
              import org.apache.commons.fileupload.servlet.ServletFileUpload;
              import org.apache.commons.fileupload.util.Streams;
              import org.apache.commons.logging.Log;
              import org.apache.commons.logging.LogFactory;
              
              import edu.iastate.its.thinkspace.core.ContextService;
              import edu.iastate.its.thinkspace.core.ProjectContext;
              import edu.iastate.its.thinkspace.core.ProjectState;
              import edu.iastate.its.thinkspace.core.utils.Status;
              
              /**
               * @author Pete
               * 
               */
              public class ProjectServlet extends HttpServlet {
              	private static Log log = LogFactory.getLog(ProjectServlet.class);
              
              	public ProjectServlet() {
              	}
              
              	public void doPost(HttpServletRequest request, HttpServletResponse response) {
              		process(request, response);
              	}
              
              	public void doGet(HttpServletRequest request, HttpServletResponse response) {
              		process(request, response);
              	}
              
              	private void process(HttpServletRequest request,
              			HttpServletResponse response) {
              		try {
              			if (ServletFileUpload.isMultipartContent(request)) {
              				processFiles(request, response);
              			} else {
              				processQuery(request, response);
              			}
              		} catch (Exception e) {
              			e.printStackTrace();
              		}
              	}
              
              	private void processQuery(HttpServletRequest request,
              			HttpServletResponse response) {
              		try {
              			String contextName = request.getParameter("context");
              			if (contextName == null) {
              				ProjectError.report(response, Status.MISSING_CONTEXT);
              				return;
              			}
              			ProjectContext context = ContextService.get().getContext(
              					contextName);
              			assert (context != null);
              			ProjectState state = (ProjectState) request.getSession()
              					.getAttribute(contextName);
              			Request req = new Request(request, response);
              			if (state != null)
              				state.request(req);
              			else {
              				response.sendRedirect("/thinkspace/logout");
              			}
              		} catch (Exception e) {
              			e.printStackTrace();
              			log.error(e);
              		}
              
              	}
              
              	private void processFiles(HttpServletRequest request,
              			HttpServletResponse response) {
              		HashMap<String, String> args = new HashMap<String, String>();
              		boolean isGWT = true;
              		try {
              			if (log.isDebugEnabled())
              				log.debug(request.getParameterMap());
              			ServletFileUpload upload = new ServletFileUpload();
              			FileItemIterator iter = upload.getItemIterator(request);
              			// pick up parameters first and note actual FileItem
              			while (iter.hasNext()) {
              				FileItemStream item = iter.next();
              				String name = item.getFieldName();
              				if (item.isFormField()) {
              					args.put(name, Streams.asString(item.openStream()));
              				} else {
              					args.put("contentType", item.getContentType());
              					String fileName = item.getName();
              					int slash = fileName.lastIndexOf("/");
              					if (slash < 0)
              						slash = fileName.lastIndexOf("\\");
              					if (slash > 0)
              						fileName = fileName.substring(slash + 1);
              					args.put("fileName", fileName);
              					// upload requests can come from smartGWT (args) or
              					// FCKEditor (request)
              					String contextName = args.get("context");
              					String model = args.get("model");
              					String path = args.get("path");
              					if (contextName == null) {
              						isGWT = false;
              						contextName = request.getParameter("context");
              						model = request.getParameter("model");
              						path = request.getParameter("path");
              						if (log.isDebugEnabled())
              							log.debug("query=" + request.getQueryString());
              					} else if (log.isDebugEnabled())
              						log.debug(args);
              					ProjectContext context = ContextService.get().getContext(
              							contextName);
              					ProjectState state = (ProjectState) request.getSession()
              							.getAttribute(contextName);
              					InputStream in = null;
              					try {
              						in = item.openStream();
              						state.getFileManager().storeFile(
              								context.getModel(model), path + fileName, in);
              					} catch (Exception e) {
              						e.printStackTrace();
              						log.error("Fail to upload " + fileName + " to " + path);
              					} finally {
              						if (in != null)
              							try {
              								in.close();
              							} catch (Exception e) {
              							}
              					}
              				}
              			}
              			// TODO: need to handle conversion options and error reporting
              			response.setContentType("text/html");
              			response.setHeader("Pragma", "No-cache");
              			response.setDateHeader("Expires", 0);
              			response.setHeader("Cache-Control", "no-cache");
              			PrintWriter out = response.getWriter();
              			out.println("<html>");
              			out.println("<body>");
              			if (isGWT) {
              				out.println("<script type=\"text/javascript\">");
              				out
              						.println("if (parent.uploadComplete) parent.uploadComplete('"
              								+ args.get("fileName") + "');");
              				out.println("</script>");
              			} else
              				out.println(getEditorResponse());
              			out.println("</body>");
              			out.println("</html>");
              			out.flush();
              		} catch (Exception e) {
              			System.out.println(e.getMessage());
              		}
              	}
              
              	private String getEditorResponse() {
              		StringBuffer sb = new StringBuffer(400);
              		sb.append("<script type=\"text/javascript\">\n");
              		sb.append("(function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})();\n");
              		sb.append("window.parent.OnUploadCompleted(0");
              		sb.append(");\n");
              		sb.append("</script>");
              		return sb.toString();
              	}
              }

              Comment


                #8
                Upload without reloading

                Hi, pboysen

                Thanks, I'm currently running the code.

                Comment


                  #9
                  Originally posted by pboysen
                  Code:
                  The following is the code for my servlet.  See the if (isGWT) section:
                  
                  package edu.iastate.its.thinkspace.core.servlet;
                  
                  import java.io.File;
                  import java.io.FileInputStream;
                  import java.io.InputStream;
                  import java.io.PrintWriter;
                  import java.util.HashMap;
                  
                  import javax.servlet.http.HttpServlet;
                  import javax.servlet.http.HttpServletRequest;
                  import javax.servlet.http.HttpServletResponse;
                  
                  import org.apache.commons.fileupload.FileItemIterator;
                  import org.apache.commons.fileupload.FileItemStream;
                  import org.apache.commons.fileupload.servlet.ServletFileUpload;
                  import org.apache.commons.fileupload.util.Streams;
                  import org.apache.commons.logging.Log;
                  import org.apache.commons.logging.LogFactory;
                  
                  import edu.iastate.its.thinkspace.core.ContextService;
                  import edu.iastate.its.thinkspace.core.ProjectContext;
                  import edu.iastate.its.thinkspace.core.ProjectState;
                  import edu.iastate.its.thinkspace.core.utils.Status;
                  
                  /**
                   * @author Pete
                   * 
                   */
                  public class ProjectServlet extends HttpServlet {
                  	private static Log log = LogFactory.getLog(ProjectServlet.class);
                  
                  	public ProjectServlet() {
                  	}
                  
                  	public void doPost(HttpServletRequest request, HttpServletResponse response) {
                  		process(request, response);
                  	}
                  
                  	public void doGet(HttpServletRequest request, HttpServletResponse response) {
                  		process(request, response);
                  	}
                  
                  	private void process(HttpServletRequest request,
                  			HttpServletResponse response) {
                  		try {
                  			if (ServletFileUpload.isMultipartContent(request)) {
                  				processFiles(request, response);
                  			} else {
                  				processQuery(request, response);
                  			}
                  		} catch (Exception e) {
                  			e.printStackTrace();
                  		}
                  	}
                  
                  	private void processQuery(HttpServletRequest request,
                  			HttpServletResponse response) {
                  		try {
                  			String contextName = request.getParameter("context");
                  			if (contextName == null) {
                  				ProjectError.report(response, Status.MISSING_CONTEXT);
                  				return;
                  			}
                  			ProjectContext context = ContextService.get().getContext(
                  					contextName);
                  			assert (context != null);
                  			ProjectState state = (ProjectState) request.getSession()
                  					.getAttribute(contextName);
                  			Request req = new Request(request, response);
                  			if (state != null)
                  				state.request(req);
                  			else {
                  				response.sendRedirect("/thinkspace/logout");
                  			}
                  		} catch (Exception e) {
                  			e.printStackTrace();
                  			log.error(e);
                  		}
                  
                  	}
                  
                  	private void processFiles(HttpServletRequest request,
                  			HttpServletResponse response) {
                  		HashMap<String, String> args = new HashMap<String, String>();
                  		boolean isGWT = true;
                  		try {
                  			if (log.isDebugEnabled())
                  				log.debug(request.getParameterMap());
                  			ServletFileUpload upload = new ServletFileUpload();
                  			FileItemIterator iter = upload.getItemIterator(request);
                  			// pick up parameters first and note actual FileItem
                  			while (iter.hasNext()) {
                  				FileItemStream item = iter.next();
                  				String name = item.getFieldName();
                  				if (item.isFormField()) {
                  					args.put(name, Streams.asString(item.openStream()));
                  				} else {
                  					args.put("contentType", item.getContentType());
                  					String fileName = item.getName();
                  					int slash = fileName.lastIndexOf("/");
                  					if (slash < 0)
                  						slash = fileName.lastIndexOf("\\");
                  					if (slash > 0)
                  						fileName = fileName.substring(slash + 1);
                  					args.put("fileName", fileName);
                  					// upload requests can come from smartGWT (args) or
                  					// FCKEditor (request)
                  					String contextName = args.get("context");
                  					String model = args.get("model");
                  					String path = args.get("path");
                  					if (contextName == null) {
                  						isGWT = false;
                  						contextName = request.getParameter("context");
                  						model = request.getParameter("model");
                  						path = request.getParameter("path");
                  						if (log.isDebugEnabled())
                  							log.debug("query=" + request.getQueryString());
                  					} else if (log.isDebugEnabled())
                  						log.debug(args);
                  					ProjectContext context = ContextService.get().getContext(
                  							contextName);
                  					ProjectState state = (ProjectState) request.getSession()
                  							.getAttribute(contextName);
                  					InputStream in = null;
                  					try {
                  						in = item.openStream();
                  						state.getFileManager().storeFile(
                  								context.getModel(model), path + fileName, in);
                  					} catch (Exception e) {
                  						e.printStackTrace();
                  						log.error("Fail to upload " + fileName + " to " + path);
                  					} finally {
                  						if (in != null)
                  							try {
                  								in.close();
                  							} catch (Exception e) {
                  							}
                  					}
                  				}
                  			}
                  			// TODO: need to handle conversion options and error reporting
                  			response.setContentType("text/html");
                  			response.setHeader("Pragma", "No-cache");
                  			response.setDateHeader("Expires", 0);
                  			response.setHeader("Cache-Control", "no-cache");
                  			PrintWriter out = response.getWriter();
                  			out.println("<html>");
                  			out.println("<body>");
                  			if (isGWT) {
                  				out.println("<script type=\"text/javascript\">");
                  				out
                  						.println("if (parent.uploadComplete) parent.uploadComplete('"
                  								+ args.get("fileName") + "');");
                  				out.println("</script>");
                  			} else
                  				out.println(getEditorResponse());
                  			out.println("</body>");
                  			out.println("</html>");
                  			out.flush();
                  		} catch (Exception e) {
                  			System.out.println(e.getMessage());
                  		}
                  	}
                  
                  	private String getEditorResponse() {
                  		StringBuffer sb = new StringBuffer(400);
                  		sb.append("<script type=\"text/javascript\">\n");
                  		sb.append("(function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})();\n");
                  		sb.append("window.parent.OnUploadCompleted(0");
                  		sb.append(");\n");
                  		sb.append("</script>");
                  		return sb.toString();
                  	}
                  }
                  I finally managed to integrate your Upload Class to my application and it works fine, thanks a lot.

                  Comment


                    #10
                    Originally posted by sjivan
                    I would be great if one of you guys can add a sample of this to the smartgwt-extensions project. If you're interested, please let me know and I'll add you as a committer.
                    Please make sure that samples are not added to the main project itself but to a new sub-project called samples. This way people using smartgwt-extensions jar in their apps would not get the samples included.

                    Also, it would be good if changes to smartgwt-extensions project be coordinated on its mailing list before commiting stuff as is typical in good OS projects. Thanks.

                    Comment


                      #11
                      thanks for those classes. but if i have more than one uploaditem, the problem is that the callback can't find the right uploaditem, because the servlet addresses the parent item. i don't know much about js, but is there a way to get a hold of the item itself instead of parent.

                      otherwise i see the solotino only in implenting a uploadmanager.

                      thx for any ideas!

                      Comment


                        #12
                        Originally posted by pascal
                        Hi, pboysen

                        Thanks, I'm currently running the code.

                        Hello, what version of smartGwt are you using, because i can't import the class UploadListener. thx

                        Comment


                          #13
                          Hi,

                          There is a minor issue in that the NamedFrame should be set to width and height "1px" not "1".

                          Cheers
                          Rob

                          Comment


                            #14
                            Originally posted by pboysen
                            Code:
                            The following is the code for my servlet.  See the if (isGWT) section:
                            
                            package edu.iastate.its.thinkspace.core.servlet;
                            
                            import java.io.File;
                            import java.io.FileInputStream;
                            import java.io.InputStream;
                            import java.io.PrintWriter;
                            import java.util.HashMap;
                            
                            import javax.servlet.http.HttpServlet;
                            import javax.servlet.http.HttpServletRequest;
                            import javax.servlet.http.HttpServletResponse;
                            
                            import org.apache.commons.fileupload.FileItemIterator;
                            import org.apache.commons.fileupload.FileItemStream;
                            import org.apache.commons.fileupload.servlet.ServletFileUpload;
                            import org.apache.commons.fileupload.util.Streams;
                            import org.apache.commons.logging.Log;
                            import org.apache.commons.logging.LogFactory;
                            
                            import edu.iastate.its.thinkspace.core.ContextService;
                            import edu.iastate.its.thinkspace.core.ProjectContext;
                            import edu.iastate.its.thinkspace.core.ProjectState;
                            import edu.iastate.its.thinkspace.core.utils.Status;
                            
                            /**
                             * @author Pete
                             * 
                             */
                            public class ProjectServlet extends HttpServlet {
                            	private static Log log = LogFactory.getLog(ProjectServlet.class);
                            
                            	public ProjectServlet() {
                            	}
                            
                            	public void doPost(HttpServletRequest request, HttpServletResponse response) {
                            		process(request, response);
                            	}
                            
                            	public void doGet(HttpServletRequest request, HttpServletResponse response) {
                            		process(request, response);
                            	}
                            
                            	private void process(HttpServletRequest request,
                            			HttpServletResponse response) {
                            		try {
                            			if (ServletFileUpload.isMultipartContent(request)) {
                            				processFiles(request, response);
                            			} else {
                            				processQuery(request, response);
                            			}
                            		} catch (Exception e) {
                            			e.printStackTrace();
                            		}
                            	}
                            
                            	private void processQuery(HttpServletRequest request,
                            			HttpServletResponse response) {
                            		try {
                            			String contextName = request.getParameter("context");
                            			if (contextName == null) {
                            				ProjectError.report(response, Status.MISSING_CONTEXT);
                            				return;
                            			}
                            			ProjectContext context = ContextService.get().getContext(
                            					contextName);
                            			assert (context != null);
                            			ProjectState state = (ProjectState) request.getSession()
                            					.getAttribute(contextName);
                            			Request req = new Request(request, response);
                            			if (state != null)
                            				state.request(req);
                            			else {
                            				response.sendRedirect("/thinkspace/logout");
                            			}
                            		} catch (Exception e) {
                            			e.printStackTrace();
                            			log.error(e);
                            		}
                            
                            	}
                            
                            	private void processFiles(HttpServletRequest request,
                            			HttpServletResponse response) {
                            		HashMap<String, String> args = new HashMap<String, String>();
                            		boolean isGWT = true;
                            		try {
                            			if (log.isDebugEnabled())
                            				log.debug(request.getParameterMap());
                            			ServletFileUpload upload = new ServletFileUpload();
                            			FileItemIterator iter = upload.getItemIterator(request);
                            			// pick up parameters first and note actual FileItem
                            			while (iter.hasNext()) {
                            				FileItemStream item = iter.next();
                            				String name = item.getFieldName();
                            				if (item.isFormField()) {
                            					args.put(name, Streams.asString(item.openStream()));
                            				} else {
                            					args.put("contentType", item.getContentType());
                            					String fileName = item.getName();
                            					int slash = fileName.lastIndexOf("/");
                            					if (slash < 0)
                            						slash = fileName.lastIndexOf("\\");
                            					if (slash > 0)
                            						fileName = fileName.substring(slash + 1);
                            					args.put("fileName", fileName);
                            					// upload requests can come from smartGWT (args) or
                            					// FCKEditor (request)
                            					String contextName = args.get("context");
                            					String model = args.get("model");
                            					String path = args.get("path");
                            					if (contextName == null) {
                            						isGWT = false;
                            						contextName = request.getParameter("context");
                            						model = request.getParameter("model");
                            						path = request.getParameter("path");
                            						if (log.isDebugEnabled())
                            							log.debug("query=" + request.getQueryString());
                            					} else if (log.isDebugEnabled())
                            						log.debug(args);
                            					ProjectContext context = ContextService.get().getContext(
                            							contextName);
                            					ProjectState state = (ProjectState) request.getSession()
                            							.getAttribute(contextName);
                            					InputStream in = null;
                            					try {
                            						in = item.openStream();
                            						state.getFileManager().storeFile(
                            								context.getModel(model), path + fileName, in);
                            					} catch (Exception e) {
                            						e.printStackTrace();
                            						log.error("Fail to upload " + fileName + " to " + path);
                            					} finally {
                            						if (in != null)
                            							try {
                            								in.close();
                            							} catch (Exception e) {
                            							}
                            					}
                            				}
                            			}
                            			// TODO: need to handle conversion options and error reporting
                            			response.setContentType("text/html");
                            			response.setHeader("Pragma", "No-cache");
                            			response.setDateHeader("Expires", 0);
                            			response.setHeader("Cache-Control", "no-cache");
                            			PrintWriter out = response.getWriter();
                            			out.println("<html>");
                            			out.println("<body>");
                            			if (isGWT) {
                            				out.println("<script type=\"text/javascript\">");
                            				out
                            						.println("if (parent.uploadComplete) parent.uploadComplete('"
                            								+ args.get("fileName") + "');");
                            				out.println("</script>");
                            			} else
                            				out.println(getEditorResponse());
                            			out.println("</body>");
                            			out.println("</html>");
                            			out.flush();
                            		} catch (Exception e) {
                            			System.out.println(e.getMessage());
                            		}
                            	}
                            
                            	private String getEditorResponse() {
                            		StringBuffer sb = new StringBuffer(400);
                            		sb.append("<script type=\"text/javascript\">\n");
                            		sb.append("(function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})();\n");
                            		sb.append("window.parent.OnUploadCompleted(0");
                            		sb.append(");\n");
                            		sb.append("</script>");
                            		return sb.toString();
                            	}
                            }
                            Can I know how is "ContextService", "ProjectContext" defined?

                            Comment


                              #15
                              Thank you

                              Hello P. Boysen,
                              I'd like to thank you. I was rather lost until I found your code.

                              Regards,

                              AAO

                              Comment

                              Working...
                              X