使用Servlet将图像上传到GWT项目中的服务器

时间:2013-08-19 10:24:06

标签: gwt servlets file-upload

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

SERVLET

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

            [...]

..而且我正确地在web.xml上进行了所需的更改 正确调用Servlet并启动方法doPost(),但FileItemIterator始终为空,就好像根本没有文件一样。 谁能猜到什么是错的?我真的不知道哪里出错了 提前谢谢

3 个答案:

答案 0 :(得分:1)

只是猜测我会说在你使用它之前在某处解析了请求。试着看看它questionanswer,似乎它几乎是同一个问题。

Sarajog

答案 1 :(得分:1)

你试过这个吗?

Iterator<FileItem> iterator = upload.parseRequest(request).iterator();

答案 2 :(得分:1)

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

即可