【问题标题】:Uploading a file or saving text using GWT使用 GWT 上传文件或保存文本
【发布时间】:2013-10-27 05:49:38
【问题描述】:

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

【问题讨论】:

  • 什么不起作用?有什么例外吗?
  • 该文件不会像 html 一样由 java 代码上传。

标签: java html gwt


【解决方案1】:

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

  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-04-10
    • 1970-01-01
    • 1970-01-01
    • 2012-03-09
    • 2017-10-06
    • 1970-01-01
    • 1970-01-01
    • 2010-11-09
    • 1970-01-01
    相关资源
    最近更新 更多