Jersey没有MessageBodyWriter,用于'java.io.File'类型的正文部分

时间:2013-02-24 10:04:31

标签: java image file-upload jersey multipartform-data

我在尝试上传文件时收到了这个错误。我有一个代码,我收到No MessageBodyWriter for body part of type 'java.io. File' and media type 'application/octet-stream'例外。我整天都试图解决这个问题而没有成功。

File file = new File(path);

    ClientConfig cc = new DefaultClientConfig();
    cc.getClasses().add(MultiPartWriter.class);
    Client client = Client.create(cc);

    WebResource webResource = client.resource(Constants.URL).path("images")
            .path("create");; 
    FormDataMultiPart fdmp = new FormDataMultiPart(); 

    fdmp.bodyPart(new FileDataBodyPart("filename", file, MediaType.APPLICATION_OCTET_STREAM_TYPE));
    fdmp.bodyPart(new FormDataBodyPart("data", imageData));

    ClientResponse response = webResource.type(MediaType.MULTIPART_FORM_DATA_TYPE).post(ClientResponse.class, fdmp); 

我尝试过其他一些版本,但我不断收到这个例外。有什么建议? :)

2 个答案:

答案 0 :(得分:0)

怎么样:

ClientConfig cc = new DefaultClientConfig();
Client client = Client.create(cc);
WebResource resource = client.resource("http://sample.com/uploadpath");
FormDataMultiPart form = new FormDataMultiPart();
File file = new File("c:/temp/file.txt");
form.field("filename", file.getName());
form.bodyPart(new FileDataBodyPart("file", file, MediaType.MULTIPART_FORM_DATA_TYPE));

ClientResponse response = resource.type(MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form);

答案 1 :(得分:0)

最后我找到了解决方案!!我在android上有这个问题

只需添加以下代码:

import com.sun.jersey.core.impl.provider.entity.InputStreamProvider; import com.sun.jersey.core.impl.provider.entity.StringProvider; .............

ClientConfig cc = new DefaultClientConfig();
cc.getClasses().add(StringProvider.class);///////// here is the magic :)
cc.getClasses().add(InputStreamProvider.class);////
cc.getClasses().add(MultiPartWriter.class);////////

WebResource webResource = Client.create(cc).resource("www......");

FormDataMultiPart multiPart = new FormDataMultiPart();
multiPart.field("bla", "bla bla", MediaType.APPLICATION_JSON_TYPE);

ClientResponse response = webResource.
            type(MediaType.MULTIPART_FORM_DATA).
            post(ClientResponse.class,multiPart);