1

我正在开发一个 GWT 应用程序,除其他功能外,它还允许用户上传图像文件并将其存储在服务器上。到目前为止,这就是我所做的..

伺服器

public class ImageUploadService extends HttpServlet {

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

public void doPost(HttpServletRequest request, HttpServletResponse response) {

    wlog("INFO: è partita la servlet");

    if (!ServletFileUpload.isMultipartContent(request))
        wlog("ERR: non è multipart!");
    ServletFileUpload fileUpld = new ServletFileUpload();

    try {
        wlog("INFO: itero file");
        FileItemIterator fileIt = fileUpld.getItemIterator(request);
        while (fileIt.hasNext()) {

            wlog("INFO: trovato file");
            FileItemStream fileStream = fileIt.next();
            BufferedInputStream in = new BufferedInputStream(
                    fileStream.openStream(), 4096);
            BufferedOutputStream out = new BufferedOutputStream(
                    new FileOutputStream("immagineSegnalazione.jpg"));

            byte[] buf = new byte[MAX_FILE_SIZE];
            int byteRead;
            while ((byteRead = in.read(buf, 0, MAX_FILE_SIZE)) >= 0) {
                out.write(buf, 0, byteRead);
            }
            in.close();
            out.flush();
            out.close();
        }

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

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

客户端模块

            [...]

        PopupPanel inserisciSegnalazionePopup = new PopupPanel();
    final FormPanel uploadForm = new FormPanel();
    uploadForm.setEncoding(FormPanel.ENCODING_MULTIPART);
    uploadForm.setMethod(FormPanel.METHOD_POST);
    inserisciSegnalazionePopup.setAutoHideEnabled(true);
    VerticalPanel holder = new VerticalPanel();
    holder.add(new Label("se puoi, allega una foto della segnalazione"));
    final FileUpload fu = new FileUpload();
    uploadForm.add(fu);
    holder.add(uploadForm);
    uploadForm.setAction(GWT.getModuleBaseURL() + "imageUpload");
    Button inviaBtn = new Button("INVIA SEGNALAZIONE");
    inviaBtn.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
            // TODO check file is image and size and other stuff


            uploadForm.submit();
        }

    });
    holder.add(inviaBtn);

            [...]

..plus 我已经正确地对 web.xml 进行了所需的更改 Servlet 被正确调用并且方法 doPost() 启动,但 FileItemIterator 始终为空,就好像根本没有文件一样.. 有人能猜出什么问题吗? 我真的看不出哪里出错了 提前谢谢你

4

3 回答 3

1

你试过这个吗?

Iterator<FileItem> iterator = upload.parseRequest(request).iterator();
于 2013-08-19T12:39:35.270 回答
1

解决方案是......只需将 .setName() 添加到 FileUpload 小部件

于 2013-08-20T12:01:22.320 回答
1

只是猜测我会说请求在您使用之前在某处解析。试着看看那个问题和它的答案,它似乎几乎是同一个问题。

萨拉约格

于 2013-08-19T12:12:09.727 回答