如何在角度和重复的同一请求中上传图像和数据?

时间:2015-08-12 00:55:51

标签: java angularjs jax-rs resteasy

我面临着在后端使用jax-rs制作角度问题的问题。 crud非常简单,有些文本字段和图像字段。

我有代码正在上传图片:

@POST
@Consumes("multipart/form-data")
public Response uploadFile(MultipartFormDataInput input) {
    ...
}

在html图层中:

<form action="http://localhost:8080/app/api/user" method="post" enctype="multipart/form-data">
   <p>
    Choose a file : <input type="file" name="file" />
   </p>
   <input type="submit" value="Upload" />
</form>

所以,我的问题是如何在这一步中做到这一点:

@POST
@Consumes("multipart/form-data")
public Response save(MultipartFormDataInput input, MyEntity entity) {
    ...
}

如果我尝试从视图层调用上面的代码,那么wildfly会给出一个错误,该错误没有找到与MyEntity参数绑定的数据。

[org.jboss.resteasy.core.ExceptionHandler] (default task-3) failed to execute: javax.ws.rs.NotSupportedException: 
Could not find message body reader for type: class mypackage.MyEntity of content type: multipart/form-data;boundary=----WebKitFormBoundaryRXVvqLpZACPylNgS

有谁知道我该怎么做?或者我应该分两步完成它?

1 个答案:

答案 0 :(得分:18)

从技术上讲,您可以从MultipartFormDataInput获取两个数据。例如

<form action="api/upload" method="post" enctype="multipart/form-data">
    Choose a file : <input type="file" name="file" />
    First name: <input type="text" name="firstname" />
    List name: <input type="text" name="lastname" />
    <input type="submit" value="Upload" />
</form>

@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response upload(MultipartFormDataInput multipart) throws IOException {

    try (InputStream in = multipart.getFormDataPart("file", InputStream.class, null);
         FileOutputStream fos = new FileOutputStream("file.png")) {
        byte[] buff = new byte[1024];
        int count;
        while ((count = in.read(buff)) != -1) {
            fos.write(buff, 0, count);
        }
    }

    String firstname = multipart.getFormDataPart("firstname", String.class, null);
    String lastname = multipart.getFormDataPart("lastname", String.class, null);
    return Response.ok(firstname + ":" + lastname).build();
}

如果你想把所有东西放到POJO中,你可以做这样的事情

public class MyEntity {

    @FormParam("firstname")
    private String firstname;

    @FormParam("lastname")
    private String lastname;

    @FormParam("file")
    private byte[] file;

    // Getter and Setters
}

然后在您的资源方法中

@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response upload(@MultipartForm MyEntity entity) throws IOException {

    try (FileOutputStream fos = new FileOutputStream("file.png")) {
        byte[] filebytes = entity.getFile();
        fos.write(filebytes);
    }

    String firstname = entity.getFirstname();
    String lastname = entity.getLastname();
    return Response.ok(firstname + ":" + lastname).build();
}

查看更多内容: