0

我有这个 servlet 来处理上传的文件并将它们存储在服务器上。

public class ImageService extends HttpServlet {

/**
 * 
 */
private static final long serialVersionUID = 1L;
private static final long MAX_FILE_SIZE = 1024 * 1024 * 1024; // 1GB

@Override
protected void doPost(final HttpServletRequest request,
        final HttpServletResponse response) {

    slog("SERVLET STARTED");

    List<String> files = new ArrayList<String>();
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {
        slog("REQUEST IS MULTIPART");
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("text/html");

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(MAX_FILE_SIZE);
        try {
            List<FileItem> items = upload.parseRequest(request);
            Iterator<FileItem> iterator = items.iterator();
            while (iterator.hasNext()) {

                FileItem item = iterator.next();

                if (!item.isFormField()) {
                    String fileName = item.getName();
                    slog("TROVATO FILE " + item.getName());
                    String root = getServletContext().getRealPath("/");
                    File path = new File(root + "/fileuploads");
                    slog("SALVO FILE IN " + path.getAbsolutePath());
                    if (!path.exists()) {
                        path.mkdirs();
                    }

                    File uploadedFile = creaFileNonAmbiguo(path, fileName);
                    slog("NOME ASSEGNATO AL FILE " + uploadedFile.getName());
                    item.write(uploadedFile);
                    response.getWriter()
                            .write(uploadedFile.getName() + ";");
                    files.add(uploadedFile.getName());
                }
            }

            response.getWriter().flush();
            slog("RISPOSTA INVIATA");

        } catch (Exception e) {
            e.printStackTrace();

        }
    } else {
        slog("LA RICHIESTA NON E' MULTIPART");
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    }
    slog("SERVLET TERMINATA");
}

@Override
protected void doGet(final HttpServletRequest request,
        final HttpServletResponse response) {

    response.setContentType("image/jpeg");
    String root = getServletContext().getRealPath("/").concat(
            "fileuploads/");
    String path = root.concat(request.getParameter("src"));

    File file = new File(path);
    response.setContentLength((int) file.length());
    FileInputStream in;
    try {
        in = new FileInputStream(file);
        OutputStream out = response.getOutputStream();
        byte[] buf = new byte[1024];
        int len = 0;
        while ((len = in.read(buf)) >= 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    } catch (IOException e) {

        e.printStackTrace();
    }

}

private File creaFileNonAmbiguo(File path, String fileName) {

    File res = new File(path + "/" + fileName);
    if (!res.exists())
        return res;
    else {
        return creaFileNonAmbiguo(path, "c".concat(fileName));
    }
}

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

}

如您所见,servlet 具有 doPost 和 doGet。在我的这部分代码中正确调用了 doGet():

[...]
String path = GWT.getModuleBaseURL() + "imageUpload?src=";

    for (String foto : result) {
        String url = path.concat(foto);
[...]

SERVLET STARTED但是 doPost 方法从未被调用,正如我从 Chrome 调试器和从未记录的事实中看到的那样。

这是我从客户端调用 doPost() 方法的方式:

inserisciSegnalazioneBtn.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {

            if (!catLst.isEnabled()
                    || catLst.getItemText(catLst.getSelectedIndex())
                            .equals("")
                    || catLst.getItemText(catLst.getSelectedIndex())
                            .equals("")
                    || descrizioneBox.getText().equals("")
                    || gsb.getText().equals("")) {
                Window.alert("ATTENZIONE: devi riempire tutti i campi");
                return;
            }

            segnalazione.setCategoria(new Categoria(catLst.getItemText(catLst
                    .getSelectedIndex())));
            segnalazione.setDescrizione(descrizioneBox.getText());
            segnalazione.setIndirizzo(gsb.getText());
            segnalazione.setUtente(LoginPanel.username);

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

                        @Override
                        public void onFailure(Throwable caught) {
                            caught.printStackTrace();
                        }

                        @Override
                        public void onSuccess(Boolean result) {
                            if (result) {
                                geocode(segnalazione);
                                uploadFrm.submit();
                                Window.alert("Inserimento avvenuto con successo");
                                MenuPanel.refreshBtn.click();
                            } else
                                Window.alert("L'inserimento ha avuto esito negativo");
                            thisPnl.hide();
                        }

                    });

        }

    });

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

    uploadFrm
            .addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {

                @Override
                public void onSubmitComplete(SubmitCompleteEvent event) {
                    Window.alert("SUBMIT COMPLETATO");
                    String res = event.getResults();
                    if (res != null && !res.equals("")) {
                        Window.alert("IL SERVER RISPONDE " + res.toString());
                        String[] uploadedFiles = res.split(";");
                        aggiornaFotoDB(uploadedFiles, segnalazione);
                    }
                }
            });

奇怪的是它在 DevMode 上正常工作,但是当我将我的 webapp 部署到 Tomcat 时它不起作用。我的代码有什么问题?

4

1 回答 1

0

原来问题出在

thisPnl.hide();

解决方案是将面板隐藏在SubmitCompleteHandler

于 2013-09-08T21:57:02.233 回答