Tuesday, June 23, 2009

GWT File UPLOAD

Client:

public void onModuleLoad() {
final FormPanel form = new FormPanel();
form.setAction(GWT.getModuleBaseURL() + "/myFormHandler");

// 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);

VerticalPanel panel = new VerticalPanel();
form.setWidget(panel);

// Create a FileUpload widget.
FileUpload upload = new FileUpload();
upload.setName("uploadFormElement");

panel.add(upload);

Button button2 = new Button("Submit", new ClickListener() {
public void onClick(Widget sender) {
form.submit();
}
});

// Add a 'submit' button.
panel.add(button2);

// Add an event handler to the form.
form.addFormHandler(new FormHandler() {

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());
}

public void onSubmit(FormSubmitEvent event) {
// TODO Auto-generated method stub

}
});

RootPanel.get().add(form);

}

.gwt.xml
add this line:


Server

public class MyFormHandler extends HttpServlet {


public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {

resp.setContentType("text/html");

FileItem uploadItem = getFileItem(req);
if(uploadItem == null) {
resp.getWriter().write("NO-SCRIPT-DATA");
return;
}

resp.getWriter().write(new String(uploadItem.get()));


}

private FileItem getFileItem(HttpServletRequest req) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);

try {
List items = upload.parseRequest(req);
Iterator it = items.iterator();

while(it.hasNext()) {
FileItem item = (FileItem) it.next();
if(!item.isFormField() && "uploadFormElement".equals(item.getFieldName())) {
return item;
}
}
}
catch(FileUploadException e){
return null;
}

return null;
}

}

4 comments:

  1. Hi

    I like this post:

    You create good material for community.

    Please keep posting.

    Let me introduce other material that may be good for net community.

    Source: Panel interview questions

    Best rgs
    Peter

    ReplyDelete
  2. Hi

    I read this post two times.

    I like it so much, please try to keep posting.

    Let me introduce other material that may be good for our community.

    Source: Panel interview questions

    Best regards
    Henry

    ReplyDelete
  3. thanks for this one...helps a lot in my project

    ReplyDelete
  4. in this method, is there a way to limit the upload file size in client side itself..??

    ReplyDelete

 
Your Ad Here ]]>