Image upload

616 views
Skip to first unread message

Deepak Singh

unread,
Nov 12, 2011, 10:32:07 AM11/12/11
to google-we...@googlegroups.com, google-a...@googlegroups.com

Hi,

I need to upload an image to GAE server and store it in datastore.
I looked for many options and found that FileUpload widget released with GWT 2.4 can do it but the restriction is that this widget must be used with FormPanel.
but i dont want to use formPanel.

Can anyone suggest me the best possible way w.r.t GWT + GAE

I am using GWT 2.4, GAE 1.5.5

Thanks
Deepak Singh

Warren Tang

unread,
Nov 12, 2011, 10:47:29 AM11/12/11
to google-we...@googlegroups.com, google-a...@googlegroups.com
You can use gwtupload widget which works without a form:
http://code.google.com/p/gwtupload/

Deepak Singh

unread,
Nov 12, 2011, 11:25:34 AM11/12/11
to google-we...@googlegroups.com
I am not interested to use any 3rd party library.
So i am trying with FileUpload with Formpanel as follows,

Html:

        <input type="file" id="uploadBtn"/>
  <button type="button" id="submitBtn">Upload</button>

Java code as follows:

final FormPanel fp = new FormPanel();
fp.setMethod(FormPanel.METHOD_POST);
fp.setEncoding(FormPanel.ENCODING_MULTIPART);
VerticalPanel vp = new VerticalPanel();
Button sub = Button.wrap(DOM.getElementById("submitBtn"));
final FileUpload fu = FileUpload.wrap(DOM.getElementById("uploadBtn"));
vp.add(fu);
vp.add(sub);
fp.add(vp);

sub.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
fp.submit();
}
});
fp.addSubmitHandler(new SubmitHandler() {
@Override
public void onSubmit(SubmitEvent event) {
greetingService.greetServer(fu.getFilename(), new AsyncCallback<String>() {
@Override
public void onSuccess(String result) {
Window.alert(result);
}
@Override
public void onFailure(Throwable caught) {
}
});
}
});
RootPanel.get().add(fp);

It is working fine but the problem is on the server side i am getting only file name(fp.getFilename()). So i am not able to get the inputstream from client.

Can you pls guide me how to get this file on server.

Thanks
Deepak

On Sat, Nov 12, 2011 at 9:17 PM, Warren Tang <warren...@gmail.com> wrote:
You can use gwtupload widget which works without a form:
http://code.google.com/p/gwtupload/

--
You received this message because you are subscribed to the Google Groups "Google Web Toolkit" group.
To view this discussion on the web visit https://groups.google.com/d/msg/google-web-toolkit/-/oHIgm4CUufsJ.
To post to this group, send email to google-we...@googlegroups.com.
To unsubscribe from this group, send email to google-web-tool...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/google-web-toolkit?hl=en.



--
Deepak Singh

Warren Tang

unread,
Nov 12, 2011, 11:41:47 AM11/12/11
to google-we...@googlegroups.com
That's a convoluted way. Below is a detailed guide: http://www.jroller.com/hasant/entry/fileupload_with_gwt

Ernesto Oltra

unread,
Nov 12, 2011, 5:50:21 PM11/12/11
to google-a...@googlegroups.com, google-we...@googlegroups.com
GWT is compiled to JavaScript: it can't do what JavaScript can't either. The trick of FileUpload is sending the form (and the file) in a hidden iframe; that way you haven't to reload the whole page. There is a good reason not to use FormPanel?

Ikai has a blog post with some sample code using GWT to upload images to appengine:
and the demo:

Armishev, Sergey

unread,
Nov 14, 2011, 4:05:18 PM11/14/11
to google-we...@googlegroups.com

Here is how I doing upload. Use Apache commons on the server and the code below should work. Let me know if you have problems

-Sergey

 

Web.xml

  <servlet>

                <servlet-name>fileuploadpackage</servlet-name>

                <servlet-class>

                com.yourcompany.server.FileUploadPackage</servlet-class>

  </servlet>

 

Client

package com.yourcompany.client;

 

import com.google.gwt.core.client.GWT;

import com.google.gwt.user.client.ui.DialogBox;

import com.google.gwt.user.client.ui.FileUpload;

import com.google.gwt.user.client.ui.FormPanel;

import com.google.gwt.user.client.ui.FormHandler;

import com.google.gwt.user.client.ui.FormSubmitEvent;

import com.google.gwt.user.client.ui.FormSubmitCompleteEvent;

import com.google.gwt.user.client.ui.VerticalPanel;

import com.google.gwt.user.client.ui.ClickListener;

import com.google.gwt.user.client.ui.Button;

import com.google.gwt.user.client.ui.Widget;

import com.google.gwt.user.client.ui.TextBox;

import com.google.gwt.user.client.Window;

 

/**

* @author Sergey Armishev

*/

public class uploadForm extends DialogBox {

 

      public uploadForm() {

            super(true,false);

          // Create a FormPanel and point it at a service.

          final FormPanel form = new FormPanel();

          form.setAction(GWT.getModuleBaseURL() + "FileUpload");

 

          // Because we're going to add a FileUpload widget, we'll need to set the

          // form to use the POST method, and multipart MIME encoding.

          form.setEncoding(FormPanel.ENCODING_MULTIPART);

          form.setMethod(FormPanel.METHOD_POST);

 

          // Create a panel to hold all of the form widgets.

          VerticalPanel panel = new VerticalPanel();

          form.setWidget(panel);

 

    // Create a FileUpload widget.

          FileUpload upload = new FileUpload();

          upload.setName("FileUpload");

          panel.add(upload);

 

          // Add a 'submit' button.

          panel.add(new Button("Submit", new ClickListener() {

            public void onClick(Widget sender) {

              form.submit();

            }

          }));

          panel.add(new Button("Cancel", new ClickListener() {

                  public void onClick(Widget sender) {

                    closeDlg();

                  }

                }));

          form.addFormHandler(new FormHandler() {

              public void onSubmit(FormSubmitEvent event) {

              }

 

              public void onSubmitComplete(FormSubmitCompleteEvent event) {

                // When the form submission is successfully completed, this event is

                // fired. Assuming the service returned a response of type text/html,

                // we can get the result text here (see the FormPanel documentation for

                // further explanation).

                Window.alert(event.getResults());

                closeDlg();

              }

            });

          this.setText("new image File");

          setWidget(form);

      }

      void closeDlg() {

            hide();

      }

}

 

On the server

package com.yourcompany.server;

 

import java.io.File;

import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.ServletOutputStream;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.*;

import org.apache.commons.fileupload.*;

import org.apache.commons.fileupload.servlet.*;

import org.apache.commons.fileupload.util.*;

import java.util.List;

import java.util.Iterator;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

 

 

public class FileUpload extends HttpServlet {

      File file;

      public FileUpload() {

      }

      /**

      *

       * @param request

      * @param response

      * @throws ServletException

      * @throws IOException

      * @Override

      */

      public void doPost(HttpServletRequest request, HttpServletResponse response)

                  throws ServletException, IOException {

 

            response.setContentType("text/html");

            response.setCharacterEncoding("UTF-8");

 

            FileItem uploadItem = getFileItem(request);

 

            if (uploadItem == null) {

                  response.getWriter().write("File not uploaded   correctly");

                  return;

            }

 

            // save the file to disk

 

            file = saveFile(uploadItem);

 

            if (file == null) {

                  response.getWriter().write("File upload error");

                  return;

            }

      }

      /**

      * Return the first FileItem of a HTTPServletRequest

      *

       * @param request

      *            The HTTPServletRequest for a file upload operation

      * @return The first file of the file upload request

      */

      @SuppressWarnings("unchecked")

      protected FileItem getFileItem(HttpServletRequest request) {

 

            FileItemFactory factory = new DiskFileItemFactory();

            ServletFileUpload upload = new ServletFileUpload(factory);

 

            try {

                  List<FileItem> items = upload.parseRequest(request);

                  Iterator<FileItem> it = items.iterator();

                  FileItem item = (FileItem) it.next();

                  return item;

            }

 

            catch (FileUploadException e) {

                  e.printStackTrace();

                  return null;

            }

      }

 

      /**

      * Save a file on a directory of the server.

      *

       * @param item

      *            file to save

      * @param sc

      *            Servlet context

      * @return error code

      */

      public File saveFile(FileItem fileItem) {

 

            try {

                  String name = fileItem.getName();

                  int index = name.lastIndexOf("/");

                  if(index > 0) {

                        name = name.substring(index);

                  } else {

                        index = name.lastIndexOf("\\");

                        if(index > 0) {

                              name = name.substring(index);

                        }

                  }

                  File file = new File("./" + name);

                  System.out.println("Saved to a file:" + file.getAbsolutePath());

                  fileItem.write(file);

                  return file;

            }

 

            catch (Exception e) {

                  e.printStackTrace();

                  return null;

            }

      }

 

}

 

 

Class FileUploadPackage

package com.yourcompany.server;

 

import java.io.File;

import java.io.IOException;

import java.io.FileInputStream;

import java.io.BufferedInputStream;

 

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import org.apache.commons.fileupload.FileItem;

/**

* @author Sergey Armishev

*/

public class FileUploadPackage extends FileUpload{

      public void doPost(HttpServletRequest request, HttpServletResponse response)

      throws ServletException, IOException {

            response.setContentType("text/html");

            response.setCharacterEncoding("UTF-8");

 

            FileItem uploadItem = getFileItem(request);

 

            if (uploadItem == null) {

                  response.getWriter().write("File not uploaded   correctly");

                  return;

            }

 

            // save the file to disk

 

            file = saveFile(uploadItem);

            //now file is in place

            if(file == null)

                  return;

           

            BufferedInputStream stream = new BufferedInputStream(new FileInputStream(file));

            try {

            array = Package.LoadContent(stream);

            } catch(Throwable ex) {

                  ex.printStackTrace();

            }

      String ret;

      if(array == null)

            ret = "Failed to read file";

      else

            ret = array.toString();

      System.out.println("Response:\n" + ret);

            setNoCahs(response);

      }

      private void setNoCahs(HttpServletResponse response) {

            //<% Response.CacheControl = "no-cache" %>

            //<% Response.AddHeader "Pragma", "no-cache" %>

            //<% Response.Expires = -1 %>

            response.setHeader("CacheControl", "no-cache");

            response.setHeader("Pragma", "no-cache");

            response.setHeader("Expires", "-1");


_____________________________________________________
This electronic message and any files transmitted with it contains
information from iDirect, which may be privileged, proprietary
and/or confidential. It is intended solely for the use of the individual
or entity to whom they are addressed. If you are not the original
recipient or the person responsible for delivering the email to the
intended recipient, be advised that you have received this email
in error, and that any use, dissemination, forwarding, printing, or
copying of this email is strictly prohibited. If you received this email
in error, please delete it and immediately notify the sender.
_____________________________________________________

Deepak Singh

unread,
Nov 15, 2011, 10:00:54 AM11/15/11
to google-we...@googlegroups.com
Thanks. I did it using Apache fileupload.

Thank you very much for all your support.

Deepak
--
Deepak Singh
Reply all
Reply to author
Forward
0 new messages