我有一个包含两部分的MultipartInput
以下是我如何从部件中提取数据的示例
@POST
@Path("/mixedMime")
@Consumes("multipart/mixed")
@ResponseStatus(HttpStatus.OK)
public String mixedMime(@Context ServletContext servletContext, MultipartInput input) throws Exception{
int index = 0;
String xmlText;
byte[] imageData;
for (InputPart part : input.getParts()) {
index++;
if(index==1){
//extract the xml test
xmlText = part.getBodyAsString()
}
if(index==2){
//extract the image data
imageData = part.getBody(???<<<<< WHAT GOES HERE >>>>???);
}
}
}
如何提取上面显示的图像数据(二进制数据)?我正在使用Jboss 7.0.2。 根据{{3}}的文档,它说我需要指定一个类?什么课?
谢谢
抱歉,我忘记了如何将数据发送到REST服务。这是客户端的相关代码。 基本上我从文件系统添加xml文件作为第一部分。一个图像作为第二部分。
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost:8080/RestTest/rest/mixedmime");
Scanner scanner =
new Scanner(new File("myXmlFile.xml")).useDelimiter("\\Z");
String messageHeader = scanner.next();
scanner.close();
FileBody bin = new FileBody(new File("dexter.jpg"));
StringBody header = new StringBody(messageHeader.toString());
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("header", header);
reqEntity.addPart("payload", bin);
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
答案 0 :(得分:3)
以下是一个简单的示例,说明如何使用RESTEasy处理多部分请求中的二进制(流)数据:
首先,定义一个类来映射你的多部分表单:
public class DataUploadForm implements Serializable {
static final long serialVersionUID = IL;
@FormParam("xml")
private String xml;
@FormParam("file")
private InputStream fileStream;
public FileUploadForm() {
super();
}
// Getters and setters here
}
然后在您的Web服务界面上,声明一个处理多部分内容并将其映射到您的自定义类的方法:
@POST
@Path("/somepath")
@Consumes({ MediaType.MULTIPART_FORM_DATA })
public Response uploadData(@MultipartForm DataUploadForm uploadForm);
在您的Web服务实现中,处理传入的请求:
@Override
public Response uploadData(DataUploadForm uploadForm) {
System.out.printf("Incoming xml data: %s\n", uploadForm.getXML());
System.out.printf("Incoming binary data: %s\n", uploadForm.getFileStream());
// Processing the input stream. For example, by using Apache Commons IO
final byte[] data ;
try {
data = IOUtils.toByteArray(uploadForm.getFileStream());
} catch (IOException ioe) {
throw new WebApplicationException("Could not read uploaded binary data");
}
return Response.ok().build();
}