通过RestyGWT使用FileUpload从GWT客户端传输文件

时间:2017-04-27 10:40:31

标签: java file-upload gwt

我有一个gwt客户端,现在我正在尝试将用户的文件(图像)传输到服务器并保存它们。你能解释一下如何使用FileUpload通过RestyGWT从GWT传输文件。我发现使用FormPanel是必须的,我认为我必须使用setAction()和submit()方法,但我使用的是RestyGWT,我无法理解如何通过restyGWT传输数据?

客户方:

private FormPanel fileUploadPanel;
private FileUpload fileUpload;
private void create() {
//Some code //
    fileUpload = new FileUpload();
    fileUploadPanel = new FormPanel();
    fileUploadPanel.setMethod(FormPanel.METHOD_POST);
    fileUploadPanel.setEncoding(FormPanel.ENCODING_MULTIPART);
    fileUpload.setName("upload");
    fileUploadPanel.setAction("http://localhost:8080/api/events/upload");
    fileUploadPanel.add(fileUpload);
//Some code//
}


 @POST
 @Path("UPLOAD_PATH")
 void uploadImage(/*i don't know how what must be here */,
             MethodCallback callback);

服务器端:

 @Path("/upload")
 @POST
 @Consumes(MediaType.MULTIPART_FORM_DATA)
 public void uploadImage(
        @FormDataParam("upload") InputStream uploadedInputStream,
        @FormDataParam("upload") FormDataContentDisposition fileDetail) {

    String uploadedFileLocation = "some_path" + fileDetail.getFileName();

    writeToFile(uploadedInputStream, uploadedFileLocation);

}

1 个答案:

答案 0 :(得分:0)

客户端

public UploadPanel()
{
   Div div = new Div();

   final FormPanel formPanel = new FormPanel();
   formPanel.setEncoding(FormPanel.ENCODING_MULTIPART);
   formPanel.setMethod(FormPanel.METHOD_POST);
   formPanel.setAction("uploadFileServletUrl");
   formPanel.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler()
   {
      @Override
      public void onSubmitComplete(SubmitCompleteEvent event)
      {
         GWT.log("event.getResults = " + event.getResults());
      }
   });

   FileUpload fileUpload = new FileUpload();
   fileUpload.getElement().setAttribute("multiple", null);
   fileUpload.setName("abcupload");
   div.add(fileUpload);
   Hidden hidden = new Hidden("id", "8"); //just an example of how to pass a parameter
   div.add(hidden);

   Button butUpload = new Button("Upload");
   div.add(butUpload);
   butUpload.addClickHandler(new ClickHandler()
   {
      @Override
      public void onClick(ClickEvent event)
      {
          formPanel.submit();
      }
   });

   formPanel.add(div);
   this.initWidget(formPanel);
}

这将POST一个标准的多部分重新发送到服务器。在那里你只需阅读部分(在这个例子中,你将有一个" id"部分,以及" abcupload"部分将是文件)。

我无法发布任何Java服务器端代码,因为我总是在服务器端使用C#,但它应该只是在多部分POST请求中读取的标准方式。