使用GWT上传文件或保存文本

时间:2013-10-26 19:50:56

标签: java html gwt

在我正在制作的这个网站中,我希望用户上传文件或在文本框中输入文本,我将保存在文件中。 对于HTML中的以下内容,

<form action="UploadServlet" method="post"
    enctype="multipart/form-data">
    <input type="file" name="file" size="50" /> <br /> 
    <input type="submit" value="Upload File" />
</form>

我想在java中使用等效代码。所以我尝试了以下内容 -

FileUpload upload = new FileUpload();
FormPanel fp = new FormPanel();
upload.setName("uploader");
fp.setEncoding(FormPanel.ENCODING_MULTIPART);
fp.setVisible(true);
fp.setMethod(FormPanel.METHOD_POST);
fp.setAction("/UploadServlet");

onModuleLoad()中的上述代码以及在RootPanel中添加对象所需的额外行。然而代码不起作用。怎么了?

(UploadServlet.java扩展了HttpServlet,它存储了用户上传的文件)

1 个答案:

答案 0 :(得分:0)

检查此代码可能对您有所帮助

  final FormPanel form = new FormPanel();
  //create a file upload widget
  final FileUpload fileUpload = new FileUpload();
  //create labels
  Label selectLabel = new Label("Select a file:");
  //create upload button
  Button uploadButton = new Button("Upload File");
  //pass action to the form to point to service handling file 
  //receiving operation.
  form.setAction("SERVLET PATH");
  // set form to use the POST method, and multipart MIME encoding.
  form.setEncoding(FormPanel.ENCODING_MULTIPART);
  form.setMethod(FormPanel.METHOD_POST);

  //add a label
  panel.add(selectLabel);
  //add fileUpload widget
  panel.add(fileUpload);
  //add a button to upload the file
  panel.add(uploadButton);

  uploadButton.addClickHandler(new ClickHandler() {
     @Override
     public void onClick(ClickEvent event) {
        //get the filename to be uploaded
        String filename = fileUpload.getFilename();
        if (filename.length() == 0) {
           Window.alert("No File Specified!");
        } else {
           //submit the form
           form.submit();                     
        }               
     }
  });