GWT FileUpload Servlet无法检索文件内容

时间:2011-12-28 23:18:23

标签: java google-app-engine gwt file-upload

我尝试开发一个可以将本地文件上传和处理到GAE服务器的Web应用程序。我试图通过使用FileUpload小部件来实现这一点,但似乎该文件无法通过http请求成功上传。

客户端代码如下所示

private void loadLocalDataDialog()
{
    final DialogBox loadBox = new DialogBox();
    loadBox.setText("Upload Local Files");

    final FormPanel form = new FormPanel();
    form.setWidth("275px");
    form.setEncoding(FormPanel.ENCODING_MULTIPART);
    form.setMethod(FormPanel.METHOD_POST);
    form.setAction(GWT.getModuleBaseURL() + "FileUploadServlet");

    VerticalPanel vp = new VerticalPanel();
    vp.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
    form.setWidget(vp);

    final FileUpload uploader = new FileUpload();
    uploader.setName("uploadlocalfile");
    vp.add(uploader);

    loadBox.add(vp);
    loadBox.center();

    HorizontalPanel buttonPanel = new HorizontalPanel();

    buttonPanel.add(new Button("Cancel", new ClickHandler()
    {
        @Override
        public void onClick(ClickEvent event)
        {
            // TODO Auto-generated method stub
            loadBox.hide();
        }
    }));

    buttonPanel.add(new Button("Submit", new ClickHandler()
    {
        @Override
        public void onClick(ClickEvent event)
        {
            // TODO Auto-generated method stub
            form.submit();
        }
    }));

    vp.add(buttonPanel);

    form.addSubmitHandler(new FormPanel.SubmitHandler()
    {
        @Override
        public void onSubmit(SubmitEvent event)
        {
            // TODO Auto-generated method stub
            String fileName = uploader.getFilename();

            if(fileName.length() == 0)
            {
                Window.alert("Error: no file is selected. Please select a file to be uploaded.");
                event.cancel();
            }
            else if(!fileName.endsWith("xml") && !fileName.endsWith("json") && !fileName.endsWith("csv"))
            {
                Window.alert("Error: file format not supported. Only supports XML, CSV and JSON");
                event.cancel();
            }
            else
                loadBox.hide();
        }
    });

    form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler()
    {
        @Override
        public void onSubmitComplete(SubmitCompleteEvent event)
        {
            // TODO Auto-generated method stub
            Window.alert(event.getResults());
        }
    });
}

我在网上做过一些研究,我发现大多数解决方案都说是因为FileUpload小部件没有名字。但是你可以看到我已经设置了小部件的名称,所以我不知道出了什么问题。

这是我的服务器端代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@SuppressWarnings("serial")
public class FileUploadServlet extends HttpServlet
{   
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{
    if(ServletFileUpload.isMultipartContent(request))
    {
        response.setContentType("text/plain");

        ServletFileUpload upload = new ServletFileUpload();
        InputStream is = null;

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

                if(item.getFieldName().equals("uploadlocalfile") && !item.isFormField())
                {
                    is = item.openStream();
                    break;
                }
            }

            if(is == null)
                response.getWriter().write("No Data");
            else
            {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                StringBuilder sb = new StringBuilder();
                String line = null;

                while((line = reader.readLine()) != null)
                    sb.append(line + "\n");
                reader.close();

                response.getWriter().write(sb.toString());
            }
        } 
        catch (FileUploadException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    else 
        response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "Request contents type is not supported by the servlet.");
}
}

无论我转移了什么文件,迭代器都不会返回任何内容,并且始终会打印“No Data”。

我尝试过ServletFileUpload.parseRequest方法,但这也不起作用。

任何想法都赞赏!感谢。

编辑:下面是我的web.xml文件中与此功能相关的部分

<servlet>
<servlet-name>loadLocalFile</servlet-name>
<servlet-class>com.meng.climatevisualizeapp.server.FileUploadServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>loadLocalFile</servlet-name>
<url-pattern>/climatevisualizeapp/FileUploadServlet</url-pattern>
</servlet-mapping>

编辑:这可能是因为http请求被解析了两次。但我无法弄清楚第一次解析的位置。

1 个答案:

答案 0 :(得分:0)

你是否进入了servlet?

我没有看到如何配置web.xml,因为它没有发布。如果你没有访问servlet,那么你需要确保在web.xml中正确定义它。

仔细检查gwt.xml文件以确保'匹配url patern,如/ FileUploadServlet,在serv.xml映射的web.xml文件中。

如果正确命名和映射,您将进入servlet。从servlet开始,带有断点,以确保首先达到这一点。然后逐步执行每一行以查看哪行抛出错误。您可能没有初始化对象或未正确配置servlet等...

我总是先检查明显的事情。

让我们知道你发现了什么。