Enviar archivo de imagen al servidor Usando la modernización
//Here i'm using PATCH
//You can use POST or anything
/*---Create ApiInterface class---*/
@Multipart
@PATCH("service/{id}/")
Call<EditProfile> uploadImage(
@Header("Authorization") String token,
@Path("id") int serviceID,
@Part MultipartBody.Part part
//@Part("banner") RequestBody requestBody
);
/*---Create API class---*/
public class NetworkClient {
private static Retrofit retrofit;
private static UrlLists urlLists = new UrlLists();
public static Retrofit getRetrofit() {
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
if (retrofit == null) {
retrofit = new Retrofit.Builder().baseUrl(urlLists.getBaseUrl()).
addConverterFactory(GsonConverterFactory.create()).client(okHttpClient).build();
}
return retrofit;
}
}
/*---Get Image from gallery---*/
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == Activity.RESULT_OK)
{
Uri selectedImage = data.getData();
String filePath = getPath(selectedImage); //Get image file path on phone
sendNewImage(filePath, "logo", selectedImage);
}
}
public String getPath(Uri uri) {
String[] projection = {MediaStore.MediaColumns.DATA};
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
String imagePath = cursor.getString(column_index);
return cursor.getString(column_index);
}
/*---Send Data---*/
private void sendNewImage(String filePath, String key, Uri imageUri) {
File file = new File(filePath);
Retrofit retrofit = NetworkClient.getRetrofit();
RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part parts = MultipartBody.Part.createFormData(key, file.getName(), requestBody);
ApiInterface uploadApis = retrofit.create(ApiInterface.class);
uploadApis.uploadImage("Bearer " + TOKEN, ID, parts).enqueue(
new Callback<EditProfile>() {
@Override
public void onResponse(Call<EditProfile> call, Response<EditProfile> response) {
if (response.isSuccessful())
{
Toast.makeText(BaseInfoActivity.this, "اطلاعات بروزرسانی شد", Toast.LENGTH_SHORT).show();
if (key.equals("logo")) {
userLogo.setImageURI(imageUri);
} else if (key.equals("banner")) {
userBanner.setImageURI(imageUri);
}
}
else
{
Toast.makeText(BaseInfoActivity.this, "مشکل در بروزرسانی، کمی دیگر امتحان کنید", Toast.LENGTH_LONG).show();
Log.d("TAG", "RESPONSE : " + response);
}
}
@Override
public void onFailure(Call<EditProfile> call, Throwable t) {
}
}
);
}
</ProgAli>