GWT + FileUpload + RESTful

时间:2014-07-08 16:27:29

标签: java gwt file-upload jersey

将我的经历记录给其他googlers:

GWT FormPanel代码:

myFormPanel = new FormPanel();
myFormPanel.setMethod(FormPanel.METHOD_POST);
myFormPanel.setAction(GWT.getModuleBaseURL() + "myGwtServlet");
myFormPanel.setEncoding(FormPanel.ENCODING_MULTIPART);

不要忘记添加字段和FileUpload小部件。

GWT的项目web.xml:

<servlet>
  <servlet-name>myGwtServlet</servlet-name>
  <servlet-class>package.server.MyGwtServletServiceImpl</servlet-class>
</servlet>

<servlet-mapping>
  <servlet-name>myGwtServlet</servlet-name>
  <url-pattern>/project/myGwtServlet</url-pattern>
</servlet-mapping>

下载apache-commons FileUpload和IO here。另外,下载最后一个mimepull,目前是mimepull-1.9.4.jar。

GWT Servlet代码:

public class MyGwtServletServiceImpl extends HttpServlet{
  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse res)
          throws ServletException, IOException {

    FormDataMultiPart form = new FormDataMultiPart();

    try {
      List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(req);
      for (FileItem item : items) {
        if (item.isFormField()) {
          form.field(item.getFieldName(), item.getString());
        } else {
          FormDataBodyPart content = new FormDataBodyPart("fileToUpload"
              , new ByteArrayInputStream(IOUtils.toByteArray(item.getInputStream()))
              , MediaType.APPLICATION_OCTET_STREAM_TYPE);
          form.bodyPart(content);
        }
      }
    } catch (FileUploadException e) {
      e.printStackTrace();
    } 

    // create Jersey Client to consume webservice
    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    client.addFilter(new HTTPBasicAuthFilter(email, password));

    WebResource webResource;
    String service = getYourWebServiceAddress();

    // initialize webservice
    webResource = client.resource(service);

    // invoke webservice
    ClientResponse webService = webResource.
        type(MediaType.MULTIPART_FORM_DATA).
        accept(MediaType.APPLICATION_JSON).
        post(ClientResponse.class, form);

    // extract JSON response
    String json = webService.getEntity(String.class);

    // write the calling result
    PrintWriter callingResult = res.getWriter();
    callingResult.println(json);
  }
}

Jersey WebService代码:

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
@Path("/yourPath")
public YourReturnClass yourMethodJson(@FormDataParam("yourParam1") String one
    , @FormDataParam("yourParam2") String two
    , @FormDataParam("yourParam3") String three
    , @FormDataParam("..") String until
    , @FormDataParam("yourParamN") String n
    , @FormDataParam("fileToUpload") InputStream fileToUpload) { /* same as GWT servlet */

  /* process your data here */

}

我希望它有所帮助:)

0 个答案:

没有答案