2013-02-24 60 views
0

我在嘗試上傳文件時收到該錯誤。我有一個代碼在下面,我收到No MessageBodyWriter for body part of type 'java.io. File' and media type 'application/octet-stream'異常。我昨天試圖解決這個問題,但沒有成功。Jersey沒有MessageBodyWriter類型爲「java.io.File」的身體部分

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); 

我已經嘗試了一些其他版本,但我不斷收到該異常。有什麼建議? :)

+0

[嘗試將文件上傳到JAX-RS(球衣)服務器]的可能重複(http://stackoverflow.com/questions/ 5772225 /試圖上傳一個文件到一個jax-rs-jersey-server) – Perception 2013-02-26 20:25:20

回答

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); 
+0

謝謝你,但也沒有成功。未找到Java類型和MIME媒體類型的消息正文編寫器。 – Cristiano 2013-02-24 10:24:11

0

最後我找到了解決辦法!我對Android的

這個問題簡單地添加以下代碼:

進口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); 
相關問題