2015-02-05 42 views
5

我正嘗試上傳圖像與改造庫。這是怎麼了上傳:Retrofit分段上傳圖像失敗

請求代碼:

@Multipart 
@POST("/customerapp/{context}/{token}/passenger/passport/add/{passengerId}") 
@Headers({ 
     "Accept: application/xml", 
     "Accept-Encoding: gzip" 
}) 
void UploadImage(
     @Path("context") String context, 
     @Path("token") String token, 
     @Path("passengerId") String passengerId, 
     @Query("fileType") String fileType, 
     @Query("imageCategory") int imageCategory, 
     @Part("imageContent") TypedFile file, 
     Callback<VJSuccessResponse> callback 
); 



public static final String BASE_URL = 
    "http://webservicetest.abc.com/extranetServices/1.1"; 

RequestInterceptor requestInterceptor = new RequestInterceptor() { 
      @Override 
      public void intercept(RequestFacade request) { 
       Log.e("Retrofit Request Body", request.toString()); 
      } 
     }; 

     RestAdapter restAdapter = new RestAdapter.Builder() 
       .setEndpoint(BackendConstants.BASE_URL) 
       .setClient(new OkClient(new OkHttpClient())) 
       .setConverter(new SimpleXMLConverter()) 
       .setLogLevel(RestAdapter.LogLevel.FULL) 
       .setRequestInterceptor(requestInterceptor) 
       .build(); 

     REST_CLIENT = restAdapter.create(BackendAPI.class); 

     REST_CLIENT.UploadImage(
       BackendConstants.CONTEXT, 
       StateObject.sSPManager.getStoredPersonalDetails().getToken(), 
       passengerId, 
       new File(filePath), 
       imageCategory, 
       new TypedFile("image/jpeg", typeFile), new Callback<VJSuccessResponse>() { 
        @Override 
        public void success(VJSuccessResponse getCallResponse, Response response) { 

        } 

        @Override 
        public void failure(RetrofitError error) { 


         Log.d(TAG, error.toString()); 
        } 
       }) 

響應:

HTTP POST http://webservicetest.abc.com/extranetServices/1.1/customerapp/customerapp/cba75eb0d5d64e16b37cca477d68d836/passenger/passport/add/56672?fileType=jpg&imageCategory=1 
Accept: application/xml 
Accept-Encoding: gzip 
Content-Type: multipart/form-data; boundary=fb1f78df-d674-4e54-9b41-32a386ca4222 
Content-Length: 6038770 
Content-Disposition: form-data; name="imageContent"; filename="userdp.jpg" 
Content-Type: image/jpeg 
Content-Length: 6038513 

Content-Transfer-Encoding: binary 
    ������JFIF����������������C������C�����,"�������������������������� 
    �����������}��!1AQa"q2���#B��R��$3br� 
(That goes long String of garbage...) 


<--- HTTP 200 http://webservicetest.abc.com/extranetServices/1.1/customerapp/customerapp/cba75eb0d5d64e16b37cca477d68d836/passenger/passport/add/56672?fileType=jpg&imageCategory=1 (109092ms) 
Date: Thu, 05 Feb 2015 14:52:28 GMTServer: GlassFish Server Open Source Edition 3.1.2.2 
X-Powered-By: Servlet/3.0 JSP/2.2 (GlassFish Server Open Source Edition 3.1.2.2 Java/Sun Microsystems Inc./1.6) 
Content-Encoding: gzip 
Content-Type: application/xml 
Content-Length: 108 
Keep-Alive: timeout=5, max=100 
Connection: Keep-Alive 
OkHttp-Selected-Protocol: http/1.1 
OkHttp-Sent-Millis: 1423148584220 
OkHttp-Received-Millis: 1423148693098 
��������������������Q(K-*��ϳU2�3PRH�K�O��K�U 
    qӵPR(.I�KI���K�U�L-V���)� 
    J-.��+N��).MNN-.�+)*M�ч�l�������u��g������ 
<--- END HTTP (108-byte body) 
retrofit.RetrofitError: org.xmlpull.v1.XmlPullParserException: Unexpected token (position:TEXT �������������������[email protected]:38 in [email protected]) 

如果我通過客戶端瀏覽器,如郵遞員或DHC發帖,請求與上述相同並且我得到了一個成功的XML響應。

請看看我對郵差客戶端的嘗試截圖。它是成功的。

enter image description here

回答

8

我也有過類似的問題,並嘗試後,我幾個小時,終於建成了圖片上傳功能,遠程服務器。
要上傳圖片,您需要正確創建API,並且還需要正確傳遞圖片。在改造的客戶,你需要設置圖像如下:

String photoName = "20150219_222813.jpg"; 
File photo = new File(photoName); 
TypedFile typedImage = new TypedFile("application/octet-stream", photo); 

RetrofitClient.uploadImage(typedImage, new retrofit.Callback<Photo>() { 

    @Override 
    public void success(Photo photo, Response response) { 
     Log.d("SUCCESS ", "SUCCESS RETURN " + response); 
    } 

    @Override 
    public void failure(RetrofitError error) { 

    } 
}); 

API設置:

@Multipart 
@POST("/") 
void uploadImage(@Part("file") TypedFile file, Callback<Photo> callback); 

遠程服務器端PHP代碼來處理圖像:

$pic = 'uploaded_images/' . $imagename . '.jpg'; 
if (!move_uploaded_file($_FILES['file']['tmp_name'], $pic)) { 
    echo "posted"; 
} 

如果有幫助任何一個請認出我..感謝很多..

+0

能否請您看看我的[嘗試發送使用JSON數據的圖像(http://stackoverflow.com/questions/29680158/how-to-send-multipart-form-data-with -retrofit)? – JJD 2015-04-21 13:55:00

+0

在Android中,我的代碼看起來很喜歡你的,但是當我發送1.5MB圖像時仍然會出現「超時」。你可以幫我嗎? – 2016-09-08 03:46:07

+0

R Beasar,這是更多的服務器端問題。您需要增加服務器PHP代碼上的圖像大小。 – techhunter 2016-09-12 00:33:53

2

爲改造2.0這工作對我來說

@Multipart 
    @Headers("Content-Type: application/json") 
    @POST("api/accounts/{id}/portrait") 
    Call<PortraitResponse> postPortrait(@Header("Authorization") String authorization, @Path("id") String id, @Part MultipartBody.Part file); 


    public void postPortrait(Uri uri) { 

     String auth = "Auth"; 
     String id = "someId"; 

     File file = new File(uri.getPath()); 

     // create RequestBody instance from file 
     RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpeg"), file); 

     // MultipartBody.Part is used to send also the actual file name 
     MultipartBody.Part body = MultipartBody.Part.createFormData("portrait", file.getName(), requestFile); 

     postPortraitCall = getAccountClient().postPortrait(auth, id, body); 
     postPortraitCall.enqueue(new Callback<PortraitResponse>() { 
      @Override 
      public void onResponse(Call<PortraitResponse> call, Response<PortraitResponse> response) { 
       if (response.isSuccessful()) { 
        // Success 
       } else { 
        // Failed 
       } 
      } 

      @Override 
      public void onFailure(Call<PortraitResponse> call, Throwable t) { 
       // Failed 
      } 
    }); 

}