Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

Send image file to server useing Retrofit

//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) {

                    }
                }
        );
    }
Comment

PREVIOUS NEXT
Code Example
Java :: arrays.aslist 
Java :: converter float para string em java 
Java :: arraylist to int array conversion in java 
Java :: java first letter to upper case 
Java :: how to make a loop in java 
Java :: write an infinite loop java 
Java :: react The href attribute is required for an anchor to be keyboard 
Java :: primitive data types in java 
Java :: binary to decimal conversion in java 
Java :: how to right align in java 
Java :: how to get last element in java 
Java :: hadoop-master error java_home is not set and could not be found 
Java :: java how to compare strings 
Java :: hello world! java 
Java :: loop through treeset java 
Java :: how to import class from another file in java 
Java :: int [] to Integer[] 
Java :: java convert edittext to double 
Java :: java 8 find in list 
Java :: setbackground color hexadecimal android 
Java :: java program for multiplication table 
Java :: Android Bitmap to Base64 String 
Java :: how to draw a rectangle in libgdx 
Java :: java list of arrays 
Java :: print string in java 
Java :: java list to array 
Java :: java String revers 
Java :: first and last digit of a number in java 
Java :: spring boot onetomany relationsion 
Java :: class declaration in java 
ADD CONTENT
Topic
Content
Source link
Name
1+2 =