0

Java Desktop应用程序中,我们可以允许用户将文件上传到 WebServer 中的文件夹中,如下所示

 File rootDir = new File( "/home/bala/temp" ) ;  
      if( FileUpload.isMultipartContent( request ) ) {  
          DiskFileUpload fileUpload = new DiskFileUpload() ;  
          Iterator iterator = fileUpload.parseRequest( request ).iterator() ;  
          while( iterator.hasNext() ) {  
                 FileItem fileItem = ( FileItem ) iterator.next() ;  
                 File file = new File( rootDir , fileItem.getName() ) ;  
                 fileItem.write( file ) ; }  
          } 
     else { throw new Exception( "Invalid request " ) ;  }  

但是我们如何在GwtGWTP中做到这一点?Gwt是否包含任何支持这一点的类?

4

1 回答 1

1

我会使用gwtupload因为它的简单性。

如果要上传多个文件,请在客户端使用 Multiuploader:

  public void onModuleLoad() {
    MultiUploader uploader = new MultiUploader();

    RootPanel.get().add(uploader);

    uploader.addOnFinishUploadHandler(new IUploader.OnFinishUploaderHandler() {
      public void onFinish(IUploader uploader) {
        if (uploader.getStatus() == Status.SUCCESS) {
          UploadedInfo info = uploader.getServerInfo();
          System.out.println("File name " + info.name);
          System.out.println("File content-type " + info.ctype);
          System.out.println("File size " + info.size);
        }
      }
    });
  }

在服务器端,只需覆盖UploadAction库提供的 servlet。

编辑:注意该方法接收一个列表FileItem,每个 FileItem 是上传文件的临时信息和内容,但不是真正的 java File。在这里,您可以将业务代码用于创建自己的dirs结构、处理它们,甚至将它们作为 blob 字段存储在 ddbb 中。在这种情况下,我们将获取所有文件并将它们存储在 temp 文件夹中(请注意,此文件夹在 linux、windows 等中是不同的)。

  public class SampleUploadServlet extends UploadAction {
    @Override
    public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException {
      String response = "";
      for (FileItem item : sessionFiles) {
        if ( ! item.isFormField()) {
          try {
            File file = File.createTempFile("upload-", ".bin");
            item.write(file);

            /// Send a customized message to the client.
            response +=  file.getAbsolutePath() + "\n";
          } catch (Exception e) {
            throw new UploadActionException(e);
          }
        }
      }

      /// Remove files from session because we have a copy of them
      removeSessionFileItems(request);

      /// Send your customized message to the client.
      return response;
    }
  }

如果您的 servlet 已经处理多部分请求,您可以使用 GWT 中的标准方式 uisngFileUploadFormPanel,尽管您会错过进度条、文件选择器样式等。

  // Add a form-panel to your document
  final FormPanel form = new FormPanel();
  form.setEncoding(FormPanel.ENCODING_MULTIPART);
  form.setMethod(FormPanel.METHOD_POST);
  form.setAction("your_upload_servlet_url");
  RootPanel.get().add(form);

  // Add a file-upload to your form
  FileUpload fu =  new FileUpload();
  form.add(fu);

  // submit your form when the user selects a file
  fu.addChangeHandler(new ChangeHandler() {
    public void onChange(ChangeEvent event) {
      form.submit();
    }
  });
于 2013-04-26T06:38:09.620 回答