Domanda

I'm developing a web-app using GWT, and I need to upload a file to the server. I've written this servlet (which I found here on stackoverflow)

public class ImageUploadService extends HttpServlet {

private static final int MAX_FILE_SIZE = 1 * 1024 * 1024;

@Override
protected void doPost(final HttpServletRequest request,
        final HttpServletResponse response) {
    wlog("INFO: LA SERVLET é PARTITA");
    boolean isMultipart = /* ServletFileUpload.isMultipartContent(request); */true;

    if (isMultipart) {
        wlog("INFO: IL CONTENUTO é MULTIPART");
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(MAX_FILE_SIZE);
        try {
            List<FileItem> items = upload.parseRequest(request);
            wlog("INFO: LISTA PARTI " + Arrays.toString(items.toArray()));
            Iterator<FileItem> iterator = items.iterator();
            while (iterator.hasNext()) {
                FileItem item = (FileItem) iterator.next();
                if (!item.isFormField()) {
                    String fileName = item.getName();

                    String root = getServletContext().getRealPath("/");
                    File path = new File(root + "/fileuploads");
                    if (!path.exists()) {
                        boolean status = path.mkdirs();
                    }

                    File uploadedFile = new File(path + "/" + fileName);
                    item.write(uploadedFile);
                    wlog("INFO: SALVATO FILE SU DISCO");
                }
            }
            wlog("FINE SERVLET");
        } catch (Exception e) {
            e.printStackTrace();

        }
    }
}

private void wlog(String s) {
    System.out.println("UPLOAD SERVLET " + s);
}
}

This servlet is correctly invoked, and the method doPost executes when I perform form.submit() on the client, but the problem is, upload.parseRequest always returns an empty list. As I seached here on SO the solution, I found that the main cause for this behaviour is that the request has already been parsed before, but, as you can see from the code I posted, I never parse the request before .parseRequest(). I'm really getting mad tryng to understand where the problem stands, as all the solutions suggested so far haven't worked. Thanks to everyone who will help spot the error.. (If it helps, I may post the client-side code, although I don't think that the issue lies there)

EDIT: inserted client code

private void inserisciSegnalazioneOK() {

    final PopupPanel inserisciSegnalazionePopup = new PopupPanel();

    VerticalPanel inseriscisegnalazioneholder = new VerticalPanel();

    final FormPanel textform = new FormPanel();
    final FormPanel uploadform = new FormPanel();
    Button inseriscisegnalazionebtn = new Button("INSERISCI SEGNALAZIONE");

    VerticalPanel textholder = new VerticalPanel();
    VerticalPanel uploadholder = new VerticalPanel();

    final Segnalazione segnalazione = new Segnalazione();
    final ListBox lbcat = new ListBox();
    for (String s : listaCategorie)
        lbcat.addItem(s);
    final TextBox descrizione = new TextBox();
    final GoogleSuggestBox gsb = new GoogleSuggestBox();
    final FileUpload fu = new FileUpload();

    textholder.add(new Label("scegli la categoria della segnalazione"));
    textholder.add(lbcat);
    textholder.add(new Label("inserisci una descrizione testuale"));
    textholder.add(descrizione);
    textholder.add(new Label("inserisci l'indirizzo della segnalazione"));
    textholder.add(gsb);

    uploadholder.add(new Label(
            "se puoi, allega una foto della segnalazione"));
    uploadholder.add(fu);

    textform.add(textholder);
    uploadform.add(uploadholder);

    inseriscisegnalazioneholder.add(textform);
    inseriscisegnalazioneholder.add(uploadform);
    inseriscisegnalazioneholder.add(inseriscisegnalazionebtn);

    inserisciSegnalazionePopup.setWidget(inseriscisegnalazioneholder);

    inseriscisegnalazionebtn.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
            // TODO Auto-generated method stub

            segnalazione.setCategoria(lbcat.getItemText(lbcat
                    .getSelectedIndex()));
            segnalazione.setDescrizione(descrizione.getText());
            segnalazione.setIndirizzo(gsb.getText());
            segnalazione.setUtente(username);
            log("INFO: upload del file " + fu.getFilename());
            textform.submit();
            uploadform.submit();

        }

    });

    uploadform.setAction(GWT.getModuleBaseURL() + "imageUpload");
    uploadform.setEncoding(FormPanel.ENCODING_MULTIPART);
    uploadform.setMethod(FormPanel.METHOD_POST);

    uploadform.addSubmitHandler(new FormPanel.SubmitHandler() {

        @Override
        public void onSubmit(SubmitEvent event) {
            // TODO Auto-generated method stub
            if (fu.getFilename().length() == 0) {
                Window.alert("Non hai eseguito l'upload di nessuna immagine");
                event.cancel();
            }
        }
    });

    textform.addSubmitHandler(new FormPanel.SubmitHandler() {

        @Override
        public void onSubmit(SubmitEvent event) {
            // TODO Auto-generated method stub

            dataLayerService.inserisciSegnalazione(segnalazione,
                    new AsyncCallback<Boolean>() {

                        @Override
                        public void onFailure(Throwable caught) {
                            // TODO Auto-generated
                            // method stub
                            caught.printStackTrace();
                        }

                        @Override
                        public void onSuccess(Boolean result) {
                            // TODO Auto-generated
                            // method stub
                            if (result) {
                                Window.alert("Inserimento avvenuto con successo");
                                inserisciSegnalazionePopup.hide();
                                gc.getLatLng(segnalazione.getIndirizzo(),
                                        new LatLngCallback() {

                                            @Override
                                            public void onFailure() {
                                                // TODO
                                                // Auto-generated
                                                // method
                                                // stub

                                            }

                                            @Override
                                            public void onSuccess(
                                                    LatLng point) {
                                                // TODO
                                                // Auto-generated
                                                // method
                                                // stub
                                                Marker m = new Marker(point);
                                                map.addOverlay(m);
                                                listaMarker.add(m);
                                            }

                                        });
                            } else
                                Window.alert("L'inserimento ha avuto esito negativo");
                        }

                    });

        }

    });

    inserisciSegnalazionePopup.setAutoHideEnabled(true);
    inserisciSegnalazionePopup.setGlassEnabled(true);
    inserisciSegnalazionePopup.center();

}
È stato utile?

Soluzione

You have to set a name to your FileUpload if you want the field to be sent out to the server.


BTW, why are you using a FormPanel for your "data" form? Why aren't you simply calling the RPC from the submit button's click? or alternatively, why aren't you putting everything in the same uploadForm and processing it all at once (data and uploaded file) on the server in your upload servlet?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top