我需要用CXF创建一个文件上传处理程序作为REST web服务。我已经能够使用如下代码上传带有元数据的单个文件:
@POST
@Path("/uploadImages")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadImage(@Multipart("firstName") String firstName,
@Multipart("lastName") String lastName,
List attachments) {
for (Attachment att : attachments) {
if (att.getContentType().getType().equals("image")) {
InputStream is = att.getDataHandler().getInputStream();
// read and store image file
}
}
return Response.ok().build();
}现在我需要添加对在同一请求中上传多个文件的支持。在这种情况下,而不是使用
内容类型,我得到了一个附件,其中包含
内容类型,该类型本身包含个人
我需要的附件。
我见过上载带有元数据的多个JSON或JAXB对象的示例,但我还无法获得处理二进制图像数据的任何内容。我尝试过直接使用MultipartBody,但它只返回
附件,而不是
嵌入其中的附件。
有没有一种方法可以递归地解析
附件以获取嵌入的附件?当然,我可以获得
附件,并自己解析文件,但我希望有更好的方法。
更新
这看起来有点杂乱无章,但下面这段代码目前已经足够好用了。不过,我很想看到一种更好的方式。
for (Attachment att : attachments) {
LOG.debug("attachment content type: {}", att.getContentType().toString());
if (att.getContentType().getType().equals("multipart")) {
String ct = att.getContentType().toString();
Message msg = new MessageImpl();
msg.put(Message.CONTENT_TYPE, ct);
msg.setContent(InputStream.class, att.getDataHandler().getInputStream());
AttachmentDeserializer ad = new AttachmentDeserializer(msg, Arrays.asList(ct));
ad.initializeAttachments();
// store the first embedded attachment
storeFile(msg.getContent(InputStream.class));
// store remaining embedded attachments
for (org.apache.cxf.message.Attachment child : msg.getAttachments()) {
storeFile(child.getDataHandler().getInputStream());
}
}
else if (att.getContentType().getType().equals("image")) {
storeFile(att.getDataHandler().getInputStream());
}
}发布于 2012-04-04 09:28:26
我已经建立了一个类似的服务来上传多个图像。我的实现如下所示(可能会有所帮助)
@Consumes({MediaType.MULTIPART_FORM_DATA,"multipart/mixed" })
public Response uploadImages(final List attachments) {
Map imageMap = new HashMap();
for (Attachment attachment : attachments) {
String imageName = attachment.getContentDisposition().getParameter("filename");
if (imageName == null) {
imageName = UUID.randomUUID().toString();
}
InputStream image = attachment.getDataHandler().getInputStream();
imageMap.put(imageName, image);
}
return imageMap;
}如果有人更喜欢bye数组而不是输入流,则可以使用此辅助方法轻松地进行转换
private static byte[] extractByteArray(final InputStream inputStream) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
byte[] dataChunk = new byte[1024 * 16];
int numRead = 0;
while (numRead != -1) {
numRead = inputStream.read(dataChunk, 0, dataChunk.length);
if (numRead != -1) {
buffer.write(dataChunk, 0, numRead);
}
}
buffer.flush();
return buffer.toByteArray();
}https://stackoverflow.com/questions/8913382
复制相似问题