Sending File and HashMap to server in GWT
Asked Answered
I

2

8

I have to send file and their properties to GWT server.

For sending a file i used form panel.

 public class BrowseFile extends DialogBox {
   // more code
   // ..

        private FormPanel getFormPanel() {
                if (formPanel == null) {
                    formPanel = new FormPanel();
                    formPanel.setMethod(FormPanel.METHOD_POST);

                    formPanel.setEncoding(FormPanel.ENCODING_MULTIPART);
                    formPanel.setAction(GWT.getHostPageBaseURL() +"UploadFileServlet");

                    formPanel.addSubmitHandler(new FormPanel.SubmitHandler(){
                        public void onSubmit(SubmitEvent event) {
                            // TODO Auto-generated method stub
                                    setFilename(fileUpload.getFilename());
                        }

                    });
                }
                return formPanel;
            }
        }   

all the properties of this file are in Hashmap GUi to add Document

there are 2 dialog box Propertybox extends DialogBox and

BrowseFile extends DialogBox

inside the constructor of PropertyBox there is BrowseFile

When PropertyBox constructor

                setSize("600px", "670px");
    setHTML("Add Document");

    setWidget(getVerticalPanel());
    browseFile = new BrowseFile();

The custom Property inside the PropertyBox depends on the class selected (Class is tree Widget)

On Server Side

public class FileUpload extends HttpServlet implements Servlet{

    private static final long serialVersionUID = 1L;
    private static final Logger log = Logger.getLogger(FileUpload.class
            .getName());
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        doPost(request, response);

    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        byte[] buffer = new byte[115200];//
        String fileName = null;
        String mimetype = null;
        String majorVersion = null;
        InputStream stream = null;

        try {

            ServletFileUpload upload = new ServletFileUpload();

            FileItemIterator iterator = upload.getItemIterator(request);
            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();
                 stream = item.openStream();

                if (item.isFormField()) {
        //                                                                      
                } else {

                    fileName = item.getName();
                    mimetype = item.getContentType();

//                                      
                }
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        int len;

        while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
            output.write(buffer, 0, len);
        }
        ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
        Session session =RootFolder.getSession();
        ContentStream contentStream = session.getObjectFactory()
                .createContentStream(fileName, output.size(), mimetype, input);


}

For Creating a document in External repository i need Document Property in hasmap

folder.createDocument(Document Property,contentStream, VersioningState.MAJOR);

The Document property should be send to this class on onClick event of Button ADD of Document property Class

*****How to send this document property to server in class FileUpload *****

Inn answered 22/8, 2012 at 11:2 Comment(0)
B
8

First of all, I'd recommend to use GWTUploader component, it eases life a lot.

http://code.google.com/p/gwtupload/

next, you will need add your hashmap (key/value) as form fields, see

http://code.google.com/p/gwtupload/issues/detail?id=8

and simply retrieve form fields on server-side component similar to the way you described:

            if (item.isFormField()) {
    //                                                                      
            } else {

it might look like:

            if (item.isFormField()) {
               paramsMap.add(item.getName(), item.getValue())
            } else {
Betthel answered 24/8, 2012 at 12:16 Comment(7)
There Can be more the 200 properties. And these property depends the class selected for the document.and there are more then 50 document class. SO adding the hashMap as form field is not a good option and also value part of hasmap is class which has 3 variable (value, dataType).Inn
@Inn I don't see why can't you add form fields to the request - after all, it's multipart data and thus it can handle (almost) unlimited number of fields. And enumeration across HashMap.entrySet isn't that big deal. I could advice to serialize HashMap into some binary stream and then send it as raw data - but this is kinda of hack and I bet you don't want this. You create fields dynamically for each type of file, marshal them into set of form fields on client and unmarshal on server, get the HashMap together with file- and that's it. Makes sense? If no - please explain, why.Betthel
hey i am not vry good in Programming and have very little knowledge of it. I will try wat you are saying. Then i ll let you know i want the same or not.Thanks.Inn
@Inn you're welcome, if you will get any questions - please shoot.Betthel
:I dont think this will work. Cause the HasHMap is not<String, String> . the HashMap is of type <String , class> this class has 3 parametes. What i have to display on gui is Key name and one parameter from this class. and waht i have to send is whole HashMap . if i use a hidden widget for remaing two parameters. Its is very dificult to create hashMap or to relate the parameters on the ServerSide.Inn
@Inn you may want to serialize your custom objects to String with either custom serializers or implementing "serializable", then write objects to "ObjectOutputStream" and then get them back to string (base64?). There's no ready-to-use solution AFAIK, so you have to get your hands dirty and write some code.Betthel
You can also serialize using JSON and then de-serialize them on the server-side. The method described by @Betthel is the best available if you want all data to be available at once on the server (i.e. single form submission)Orlandoorlanta
T
1

Why don't use a sequence of requests?

  1. Client: Upload a file. Use FormPanel.
    Server: saves the file and returns new fileId (if successful)

  2. Client: (from onSubmitCompleted) sends file's data together with its fileId. Use whatever data structure you need
    Server: stores the file info fields into DB.

Tetra answered 24/8, 2012 at 21:30 Comment(2)
:what do mean by new field. how to return it. Can u give a small example.Inn
it was new file ID, not "field" in my messageTetra

© 2022 - 2024 — McMap. All rights reserved.