0

在我正在制作的这个站点中,我希望用户上传文件或在文本框中输入文本,然后将其保存在文件中。对于以下 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 并存储了用户上传的文件)

4

1 回答 1

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();                     
        }               
     }
  });
于 2013-10-26T21:03:49.960 回答