2017-02-20 74 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的任何示例? –