0

I'm trying to upload an image from Android to server with retrofit.... Is it posible? I can't find any example, but it's possible with volley Edit: the backend expects Base64 it's only for save the image. Thanks for your help!!

Diego Cardenas
  • 55
  • 2
  • 13
  • 3
    Possible duplicate of [How to Upload Image file in Retrofit 2](https://stackoverflow.com/questions/39953457/how-to-upload-image-file-in-retrofit-2) – Kevin Kurien Dec 18 '18 at 04:42
  • 1
    Yes, but how you'd do it depends on the way the server is written. We cann't actually answer how to do it. – Gabe Sechan Dec 18 '18 at 04:42

2 Answers2

0

Model class

public class MyModel {

@SerializedName("name")
String Name;

@SerializedName("image")
String Image;

@SerializedName("response")
String Response;

public MyModel(String name, String image, String response) {
    Name = name;
    Image = image;
    Response = response;
}

public String getName() {
    return Name;
}

public void setName(String name) {
    Name = name;
}

public String getImage() {
    return Image;
}

public void setImage(String image) {
    Image = image;
}

public String getResponse() {
    return Response;
}

public void setResponse(String response) {
    Response = response;
}
 }

Interface

public interface MyInterFace {

@FormUrlEncoded
@POST("Filename.php")
Call<MyModel> imgUp(@Field("name") String name, @Field("image") String image);
}

Main Activity

public class MainActivity extends AppCompatActivity {

EditText name;
ImageView imageView;
Button button, upload;
static final int IMG_REQ = 777;
Bitmap bitmap;``

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    name = findViewById(R.id.name);
    imageView = findViewById(R.id.image);
    button = findViewById(R.id.button);
    upload = findViewById(R.id.button_upload);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            selectImage();
        }
    });
    upload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            upMy();
        }
    });


}

    public void upMy() {
    String Img = imageToString();
    String name3 = name.getText().toString();
    MyInterFace interFace = ApiClient.getApi().create(MyInterFace.class);
    Call<MyModel> call = interFace.imgUp(name3, Img);
    call.enqueue(new Callback<MyModel>() {
        @Override
        public void onResponse(Call<MyModel> call, Response<MyModel> response) {
            MyModel myModel = response.body();
            imageView.setVisibility(View.GONE);
            name.setVisibility(View.GONE);
            button.setEnabled(true);
            upload.setEnabled(false);
            name.setText("");
            Toast.makeText(MainActivity.this, myModel.getResponse(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailure(Call<MyModel> call, Throwable t) {

        }
    });
}

    private void selectImage() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(intent, IMG_REQ);
   }

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

    if (requestCode == IMG_REQ && resultCode == RESULT_OK && data != null) {
        Uri path = data.getData();
        try {
            bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), path);
            imageView.setImageBitmap(bitmap);
            imageView.setVisibility(View.VISIBLE);
            name.setVisibility(View.VISIBLE);
            button.setEnabled(false);
            upload.setEnabled(true);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

    private String imageToString() {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
    byte[] imagByte = byteArrayOutputStream.toByteArray();
    return Base64.encodeToString(imagByte, Base64.DEFAULT);
}
}

Apiclient

public class ApiClient {
public static final String BASE_URL = Your Base URL;
public static Retrofit retrofit;

public static Retrofit getApi() {
    if (retrofit == null) {
    retrofit = new Retrofit.Builder().baseUrl(BASE_URL)
  .addConverterFactory(GsonConverterFactory.create()).build();
    }
    return retrofit;
}
}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="30dp"
tools:context="shuan.sam.MainActivity">

<ImageView
    android:id="@+id/image"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:padding="5dp"
    android:visibility="gone"
    />

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/name"
    android:layout_below="@+id/image"
    android:visibility="gone"
    />
<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/button"
    android:text="Choose"
    android:layout_below="@+id/name"
    android:layout_marginTop="10dp"
    />

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/button_upload"
    android:text="Upload"
    android:layout_below="@+id/button"
    android:layout_marginTop="10dp"
    android:enabled="false"
    />

</RelativeLayout>
Praveen
  • 946
  • 6
  • 14
0

if your backend expects base64 as an image you can convert an image to base64 and send it as a string if your backend expects it as the whole image you can send the image using multipart

code to convert an image to base64

Bitmap bm = BitmapFactory.decodeFile("/path/to/image.jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object   
byte[] b = baos.toByteArray(); 
String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);

multipart example

@Multipart
@POST("user/updateprofile")
Observable<ResponseBody> updateProfile(@Part("user_id") RequestBody id,
                                       @Part("full_name") RequestBody fullName,
                                       @Part MultipartBody.Part image,
                                       @Part("other") RequestBody other);

//pass it like this
File file = new File("/storage/emulated/0/Download/Corrections 6.jpg");
RequestBody requestFile =
        RequestBody.create(MediaType.parse("multipart/form-data"), file);

// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body =
        MultipartBody.Part.createFormData("image", file.getName(), requestFile);

// add another part within the multipart request
RequestBody fullName = 
        RequestBody.create(MediaType.parse("multipart/form-data"), "Your Name");

service.updateProfile(id, fullName, body, other);

reference

ॐ Rakesh Kumar
  • 1,318
  • 1
  • 14
  • 24
akshay_shahane
  • 4,423
  • 2
  • 17
  • 30