2016-02-28 108 views
1

因此,繼承人的事情,文件成功上傳爲「photo.png」,但是當我從瀏覽器打開照片照片已損壞。當我下載照片在我的電腦本地打開它時,照片已損壞。Retrofit 2圖片上傳成功,但圖片上傳損壞的文件

不知道爲什麼。

繼承人的改造端點:

@Multipart 
@POST("alerts/{alertId}/photo/") 
Call<Object> uploadPhotoStill(@Header("Authorization") String credentials, @Path("alertId") int alertId, 
           @Part("photo\"; filename=\"picture_taken.jpeg\" ") RequestBody photo); 

這裏是我如何使用它:我正在抓的是來自拍照與攝像對象返回的字節數組。

private void initCamera() { 
    if (camera == null) { 
     camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT); 

     Camera.Parameters params = camera.getParameters(); 
     params.setPictureFormat(ImageFormat.JPEG); 

     camera.setParameters(params); 
    } 
} 

/** 
* Called when image data is available after a picture is taken. 
* The format of the data depends on the context of the callback 
* and {@link Camera.Parameters} settings. 
* 
* @param data a byte array of the picture data 
* @param camera the Camera service object 
*/ 
@Override 
public void onPictureTaken(byte[] data, Camera camera) { 
    Log.d(TAG, "onPictureTaken() called with: " + "data = [" + Arrays.toString(data) + "], camera = [" + camera + "]"); 
    handleTakenStill(data); 
} 

private void handleTakenStill(byte[] data) { 
    Log.d(TAG, "handleTakenStill() was called"); 

    RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpeg"), data); 

    havenApi.uploadPhotoStill(Utils.encodeUserCredentials(), getCurrentAlert().getId(), requestBody).enqueue(new Callback<Object>() { 
     @Override 
     public void onResponse(Response<Object> response, Retrofit retrofit) { 
      if (response.isSuccess()) { 
       Log.d(TAG, "handleTakenStill.onResponse success: " + response.body().toString()); 
      } else { 
       Log.e(TAG, "handleTakenStill.onResponse error: " + response.message()); 
      } 
     } 

     @Override 
     public void onFailure(Throwable t) { 
      Utils.logOnFailureRequest(TAG, t); 
     } 
    }); 
} 

上傳照片後總會調用成功。但照片總是上傳損壞,我不知道爲什麼。

+0

是在PNG格式的圖像? – TheSunny

+0

@TheSunny圖像只是從onPictureTaken方法中抓取的一個byteArray – User051691

+0

那麼圖像是哪種格式?上面onPictureTaken方法的註釋表明,數據的格式取決於傳入的參數。您應該檢查一下,看看是否可能是問題的原因。 – TheSunny

回答

0

我從來沒有得到與改造工作。但是我可以用OkHttp來完成。

如果你想知道如何在這裏是解決方案:

/** 
* Called when image data is available after a picture is taken. 
* The format of the data depends on the context of the callback 
* and {@link Camera.Parameters} settings. 
* 
* @param data a byte array of the picture data 
* @param camera the Camera service object 
*/ 
@Override 
public void onPictureTaken(byte[] data, Camera camera) { 
    Log.d(TAG, "onPictureTaken() called with: " + "data = [" + Arrays.toString(data) + "], camera = [" + camera + "]"); 
    handleTakenStill(data); 
} 

private void handleTakenStill(byte[] data) { 
    Log.d(TAG, "handleTakenStill() was called"); 

    Observable.create(uploadPhoto(data)) 
      .subscribeOn(Schedulers.io()) 
      .observeOn(AndroidSchedulers.mainThread()) 
      .subscribe(new Subscriber<com.squareup.okhttp.Response>() { 
       @Override 
       public void onCompleted() { 
        Log.d(TAG, "onCompleted() was called"); 
       } 

       @Override 
       public void onError(Throwable e) { 
        Utils.logOnFailureRequest(TAG, e); 
       } 

       @Override 
       public void onNext(com.squareup.okhttp.Response response) { 
        if (response.isSuccessful()) { 
         Log.d(TAG, "handleTakenStill.onResponse success: " + response.body().toString()); 
        } else { 
         Log.e(TAG, "handleTakenStill.onResponse error: " + response.message()); 
        } 
       } 
      }); 
} 

@NonNull 
private Observable.OnSubscribe<com.squareup.okhttp.Response> uploadPhoto(final byte[] data) { 
    return new Observable.OnSubscribe<com.squareup.okhttp.Response>() { 
     @Override 
     public void call(Subscriber<? super com.squareup.okhttp.Response> subscriber) { 
      OkHttpClient client = new OkHttpClient(); 

      RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM) 
        .addFormDataPart("camera", "picture_taken.jpg", RequestBody.create(MediaType.parse("image/jpeg"), data)) 
        .build(); 

      Request request = new Request.Builder() 
        .url(url) 
        .post(requestBody) 
        .addHeader("content-type", "multipart/form-data") 
        .addHeader("authorization", Utils.encodeUserCredentials()) 
        .addHeader("accept", "application/json") 
        .addHeader("cache-control", "no-cache") 
        .build(); 

      try { 
       com.squareup.okhttp.Response response = client.newCall(request).execute(); 
       subscriber.onNext(response); 
       subscriber.onCompleted(); 
       if (!response.isSuccessful()) { 
        subscriber.onError(new Exception("Error uploading photo")); 
       } 
      } catch (IOException e) { 
       subscriber.onError(e); 
      } 
     } 
    }; 
} 
0

1)如評論中所述檢查照片類型。有時swith到JPG格式解決問題。

2)儘量把作爲參數傳遞給RequestBody不僅僅是文件,或文件路徑(RequestBode對象的另一個構造函數)

我用下面的代碼沒有問題,但我發送文件作爲表單數據:

@Multipart 
    @POST("/api/tour/upload") 
    Call<MainFileModel> uploadTourFiles(@PartMap Map<String, RequestBody> params); 


    File mainFile = new File(fileLoad.getFile()); 
    Map params = new Map<>(); 
    params.put("file\"; filename=\"" + mainFile.getName(), 
     RequestBody.create(MediaType.parse("multipart/form-data"),         mainFile));; 


//And Make call here! 
+0

我已經這樣做了。一樣。沒有工作。 – User051691