我创建了widget,我直接添加到根面板
public class FileUploadWidget extends VerticalPanel {
public FileUploadWidget() {
super();
final FormPanel form = new FormPanel();
form.setMethod(FormPanel.METHOD_POST);
form.setEncoding(FormPanel.ENCODING_MULTIPART);
form.setAction("/FileUpload");
form.setWidget(this);
final FileUpload fileUpload = new FileUpload();
fileUpload.setName("uploadFormElement");
this.add(fileUpload);
Label maxUpload = new Label();
maxUpload.setText("Maximum upload file size: 1MB");
this.add(maxUpload);
Button button = new Button("Submit");
button.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
form.submit();
}
});
this.add(button);
form.addSubmitCompleteHandler(new SubmitCompleteHandler() {
public void onSubmitComplete(SubmitCompleteEvent event) {
Window.alert(event.getResults());
}
});
}
}
我创建了servlet
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/plain");
FileItem uploadItem = getFileItem(request); //BREAKPOINT
if (uploadItem == null) {
response.getWriter().write("NO-SCRIPT-DATA");
return;
}
try {
uploadItem.write(new File("newfile.txt"));
} catch (Exception e) {
response.getWriter().write("ERROR");
}
response.getWriter().write("OK");
}
private FileItem getFileItem(HttpServletRequest request) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator it = items.iterator();
while (it.hasNext()) {
FileItem item = (FileItem) it.next();
if (!item.isFormField()
&& "uploadFormElement".equals(item.getFieldName())) {
return item;
}
}
} catch (FileUploadException e) {
return null;
}
return null;
}
}
我把我的web.xml文件映射为servlet
<servlet>
<servlet-name>FileUpload</servlet-name>
<servlet-class>my.web.app.GwtFileUpload.server.FileUploadServlet</servlet-class>
</servlet>
....
<servlet-mapping>
<servlet-name>FileUpload</servlet-name>
<url-pattern>/FileUpload</url-pattern>
</servlet-mapping>
现在当我选择文件,然后调用提交, 当我使用firefox时没有发生任何事情(我得到的只是SubmitEvent),我的断点,我在servlet代码中标记的永远不会到达
当我在chrome下尝试相同的代码时,它会进入servlet,但它没有找到任何文件
任何人都可以解释为什么会有这么不同的行为,以及我如何解决它?
答案 0 :(得分:3)
FileUpload
小部件包装HTML
元素。如果要将此小部件提交给服务器,则必须与FormPanel
一起使用。
因此,有必要将fileupload添加到FormPanel
。您已将其直接添加到Panel
。
请替换代码
this.add(fileUpload);
到
form.add(fileUpload);
有关详情,请仔细阅读http://www.tutorialspoint.com/gwt/gwt_fileupload_widget.htm
链接答案 1 :(得分:2)
将fileUpload控件添加到FormPanel
,因为FileUpload
widget
(实现HasName的那些)将被提交到服务器(如果它们包含在此面板中)。
执行fileupload
后,您已将form.setWidget(this);
添加到Verticlepanel中。喜欢
this.add(fileUpload);
form.setWidget(this);
答案 2 :(得分:0)
我建议使用gwtupload库,它可以节省大量时间编写自己的代码,并为您的应用提供许多功能,如自定义按钮,进度条,文件扩展名,大小限制等。
您拥有此GettingStarted和此example页。