Question Detail

I want to upload Image on the server from Mobile's Gallery or by clicking from Camera. I am able to click the image from the camera but don't have any idea how can I upload the image from gallery or Camera on server.
 


Thread Reply

Hemant Sharma

- 9 months ago

First Import some Retrofit dependency in your gradle file

compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'

 

 

ApiClient.java

import com.google.gson.Gson;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiClient {
    public static final String BASE_URL = "http://vbageTech.com";
    private static Retrofit retrofit = null;
    private static int i = 0;

    public static Retrofit getClient(Gson gson, OkHttpClient okHttpClient) {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create(gson)).client(okHttpClient).build();
        }
        return retrofit;
    }
}

UploadImageService.java

import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Header;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;

/**
 * Created by Hemant on 2/21/2018.
 */
public interface UploadImageService {
    @Multipart
    @POST("/fundook/api/profile/userImage")
    Call<ResponseBody> postImage(@Part MultipartBody.Part image, @Part("profilePic") RequestBody name);
}

 

put Below code in your Activity where you want to upload Process

import java.io.File;
import java.util.ArrayList;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
 //..........Your Activity Code
@Override
protected void onCreate(Bundle savedInstanceState) {

//...........your code

userImgEdit_ImageView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        selectImagesMethod();
    }
});
//...........your code
}
void selectImagesMethod() {
    final CharSequence[] items = {"Take Photo", "Choose from Library", "Cancel"};
    AlertDialog.Builder builder = new AlertDialog.Builder(thiss);
    builder.setTitle("Add Photo!");
    builder.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            boolean result = Utility.checkPermission(thiss);

            if (items[item].equals("Take Photo")) {
                userChoosenTask = "Take Photo";
                if (result)
                    cameraIntent();

            } else if (items[item].equals("Choose from Library")) {
                userChoosenTask = "Choose from Library";
                if (result)
                    galleryIntent();

            } else if (items[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();

}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == SELECT_FILE)
            onSelectFromGalleryResult(data);
        else if (requestCode == REQUEST_CAMERA)
            onCaptureImageResult(data);
    }
}
@SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
    Uri selectedFileUri = data.getData();
    selectedFilePath = FilePath.getPath(this, selectedFileUri);
    Log.i(TAG, "Selected File Path: " + selectedFilePath);
    System.out.println(selectedFilePath.replace(" ", "") + " onSelectFromGalleryResult : __EDITACCUNT_2____ ");
    // uploadProfileImage(selectedFilePath);
    uploadProfileImage(selectedFilePath);
    lastLogginUser(selectedFilePath);
}

 

private void onCaptureImageResult(Intent data) {
    Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    //File destination = new File(Environment.getExternalStorageDirectory(),System.currentTimeMillis() + ".jpg");
    File destination = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + getString(R.string.app_name) + "/", Pref.getString(thiss, "userName_pref").replace(" ", "_") + "_Profile" + System.currentTimeMillis() + ".jpg");
    FileOutputStream fo;
    try {
        destination.createNewFile();
        fo = new FileOutputStream(destination);
        fo.write(bytes.toByteArray());
        fo.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println(" onCaptureImageResult : __EDITACCUNT____ " + destination.getPath());
    //uploadProfileImage("/storage/emulated/0/FunBook/Hemant_Sharma_Profile1519063771703.jpg");
    //setimage(thumbnail);
    //userImg_ImageView.setImageBitmap(thumbnail);
    uploadProfileImage(destination.getPath());
    lastLogginUser(destination.getPath());
}
private void galleryIntent() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);//
    startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
}

private void cameraIntent() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent, REQUEST_CAMERA);
}

 


 void uploadProfileImage(final String filePath) {

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                if (message.startsWith("{\"status\"")) {
                    System.out.println("_______________________START_RESPONCE___________________________________");
                    System.out.println("^^^^^^^^^^^^^" + message);
                }
            }
        });


        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

// Change base URL to your upload server URL.
        UploadImageService service = new Retrofit.Builder()
                .baseUrl(ApiClient.BASE_URL)
                .client(client).build()
                .create(UploadImageService.class);
        File file = new File(filePath);
        RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("profilePic", file.getName(), reqFile);
        RequestBody name = RequestBody.create(MediaType.parse("application/text; charset=utf-8"), "profilePic");
        Call<ResponseBody> req = service.postImage(body, name);
        req.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                // Do Something
                Log.d("", response.isSuccessful() + "___" + response.raw());
                onStart();
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Toast.makeText(this, "Fail: " + t.getMessage().toString(), Toast.LENGTH_SHORT).show();
                t.printStackTrace();
            }
        });
    }