2017-02-20 148 views
1

我有一個函數與改造要求上傳圖片這樣如何使用Retrofit Android上傳圖片?

void uploadPhoto(File file) { 
    RequestBody photo = RequestBody.create(MediaType.parse("application/image"), file); 
    RequestBody body = new MultipartBuilder() 
      .type(MultipartBuilder.FORM) 
      .addFormDataPart("photo", file.getName(), photo) 
      .build(); 

    fragment.showProgressDialog(fragment.loading); 
    fragment.getApi().uploadPhoto(PrefHelper.getString(PrefKey.TOKEN), body) 
      .observeOn(AndroidSchedulers.mainThread()) 
      .subscribeOn(Schedulers.io()) 
      .subscribe(new Observer<GenericResponse>() { 
       @Override 
       public void onCompleted() { 

       } 

       @Override 
       public void onError(Throwable e) { 
        fragment.dismissProgressDialog(); 
        Timber.e(e.getMessage()); 
       } 

       @Override 
       public void onNext(GenericResponse response) { 
        fragment.dismissProgressDialog(); 

        if (response.getCode() == 1) { 
         fragment.showSuccessDialog("Saving success", false); 
         userInfo(); 
        } 

       } 
      }); 
} 

,爲例子,我有一個按鈕來上傳圖片在我的片段

@OnClick(R.id.btnChangePicture) 
    void onChangePictureClicked() { 

} 

要我把

什麼碼

OnChangePictureClicked

所以我可以從圖庫中選擇圖片,然後我向API請求它。

空隙uploadPhoto(文件文件)

由於

+0

所以你有問題獲取圖像源或上傳到服務器? – TruongHieu

+0

我的問題是越來越圖像來源@TruongHieu –

+0

你能提供更多關於你想要採取什麼來源的信息嗎?像畫廊或相機什麼的..? – TruongHieu

回答

1

將圖像轉換爲字節數組,然後創建一個對象Dto,如下例所示,並通過Retrofit將其發送到服務器。

@Data 
public class SetProfileImageRequestDto { 
    @SerializedName("Token") 
    private String token; 

    @SerializedName("Stream") 
    private byte[] image; 

}

改造API服務:

@POST("SetProfileImage/") 
    Observable<ResultResponseDto> setProfileImage(@Body SetProfileImageRequestDto profileImageRequestDto); 

希望工程。

+0

如何從圖庫中獲取圖像?如何獲取我想要發送給服務器的圖像文件或數據? –

+0

你的意圖ACTION_PICK將返回一個Uri,然後檢查:http://stackoverflow.com/questions/10296734/image-uri-to-bytesarray – MGDiez

1

創建活動或片段的Uri對象。

private Uri selectedImage; 

之後,您將在onActivityResult中獲得圖庫結果。

 @Override 
      protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
       super.onActivityResult(requestCode, resultCode, data); 
       if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) { 
        selectedImage = data.getData(); 
       } 
      } 

然後在你的onChangePictureClicked方法中。

@OnClick(R.id.btnChangePicture) 
     void onChangePictureClicked() { 
      if(selectedImage !=null){ 
      uploadPhoto(new File(selectedImage.getPath())); 
      } 
     } 
+0

它不起作用 –

0

您可以使用multipart進行改造,請查看這個使用改進的圖像上傳示例,它最適合您。

它爲我工作。

//Create Upload Server Client 
     ApiService service = RetroClient.getApiService(); 

     //File creating from selected URL 
     File file = new File(imagePath); 

     // create RequestBody instance from file 
     RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file); 

     MultipartBody.Part body = 
       MultipartBody.Part.createFormData("uploaded_file", file.getName(), requestFile); 

     Call<Result> resultCall = service.uploadImage(body); 

     resultCall.enqueue(new Callback<Result>() { 
      @Override 
      public void onResponse(Call<Result> call, Response<Result> response) { 

       progressDialog.dismiss(); 

       // Response Success or Fail 
       if (response.isSuccessful()) { 
        if (response.body().getResult().equals("success")) 
         Snackbar.make(parentView, R.string.string_upload_success, Snackbar.LENGTH_LONG).show(); 
        else 
         Snackbar.make(parentView, R.string.string_upload_fail, Snackbar.LENGTH_LONG).show(); 

       } else { 
        Snackbar.make(parentView, R.string.string_upload_fail, Snackbar.LENGTH_LONG).show(); 
       } 

       /** 
       * Update Views 
       */ 
       imagePath = ""; 
       textView.setVisibility(View.VISIBLE); 
       imageView.setVisibility(View.INVISIBLE); 
      } 

      @Override 
      public void onFailure(Call<Result> call, Throwable t) { 
       progressDialog.dismiss(); 
      } 
     }); 

http://www.pratikbutani.com/2016/06/android-upload-image-file-using-retrofit-2-0/ 
+0

Rx Java Observable的任何示例? –