首页 > 解决方案 > 如何在 @MultipartForm Pojo 中使用 UUID?

问题描述

我想将我的 DTO 中的 UUID转移到我的资源方法中。

我的方法:

    @POST
    @Path(("/upload"))
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    @Produces(MediaType.APPLICATION_JSON)
    public Response sendMultipartData(@MultipartForm MultipartBodyRequestDto data) {
      // Do stuff [...]
        return Response.ok().entity(responseDto).build();
    }

我的 DTO:

public class MultipartBodyRequestDto {

    // Other properties [...]

    @NotNull
    @FormParam("file")
    @PartType(MediaType.APPLICATION_OCTET_STREAM)
    public InputStream file;

    @NotNull
    @FormParam("id")
    @PartType(MediaType.TEXT_PLAIN) // <-- What do I have to select here ?
    public UUID id;
}

我收到此错误:

“RESTEASY007545:找不到媒体类型的 MessageBodyReader:text/plain;charset=UTF-8 和类类型 java.util.UUID”

切换到 String 和 @PartType(MediaType.TEXT_PLAIN) 时,它可以工作,但我必须自己转换 id。

Resteasy 应该能够转换它,毕竟我在其他端点中使用 UUID,如下所示:

@GET
@Path("/{id}")
public Response get(@PathParam("id") @NotNull UUID id) {
   // Do stuff [...]
}

我是否必须实现特定的MessageBodyReader

标签: restmultipartform-dataresteasyquarkus

解决方案


您需要提供一个MessageBodyReader<UUID>知道如何读取数据的。类似于以下内容:

@Provider
public class UuidMessageBodyReader implements MessageBodyReader<UUID> {
    @Override
    public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType) {
        return type.isAssignableFrom(UUID.class);
    }

    @Override
    public UUID readFrom(final Class<UUID> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws IOException, WebApplicationException {
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            final byte[] buffer = new byte[256];
            int len;
            while ((len = entityStream.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            return UUID.fromString(out.toString(resolve(mediaType)));
        } finally {
            entityStream.close();
        }
    }

    private String resolve(final MediaType mediaType) {
        if (mediaType != null) {
            final String charset = mediaType.getParameters().get("charset");
            if (charset != null) {
                return charset;
            }
        }
        return "UTF-8";
    }
}

请注意,这只是一个简单的示例,可能有更有效的方法来执行此操作。

它在您的另一个端点上工作的原因是它只会返回UUID.toString(). 但是,没有读取类型的默认方法,因为没有UUID.valueOf()方法。


推荐阅读