Phần này nối tiếp bài viết https://zezo.dev/view/huong-dan-su-dung-retrofit-upload-file-anh-len-api/
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.squareup.picasso.Picasso;
import java.io.File;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
private static final int PICK_IMAGE_REQUEST_CODE = 100;
private Uri imageUri;
private static final String BASE_URL = "http://10.0.2.2:3000/api/"; // Replace with your base URL
static final String TAG = "zzzzzzzz";
ImageView img_preview;
TextView tv01;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv01 = findViewById(R.id.tv01);
img_preview = findViewById(R.id.img_preview);
findViewById(R.id.btn_browsefile).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
pickImage();
}
});
findViewById(R.id.btn_upload).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
uploadFile();
}
});
if (Build.VERSION.SDK_INT >= 30){
if (!Environment.isExternalStorageManager()){
Intent getpermission = new Intent();
getpermission.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
startActivity(getpermission);
}
}
}
private void pickImage() {
// Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(intent, PICK_IMAGE_REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST_CODE && resultCode == RESULT_OK) {
imageUri = data.getData();
Log.d(TAG, "onActivityResult: " + imageUri);
tv01.setText(imageUri.toString());
}
}
private void uploadFile() {
if (imageUri == null) {
Log.d(TAG, "uploadFile: URI null");
tv01.setText("URI file null");
return;
}
File file = new File(getRealPathFromURI(imageUri));
Log.d(TAG, "uploadFile: " + file.toString());
RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
// *** chú ý cái này MediaType.parse("image/*") phải để là image/* thì trên server mới nhận diện ra file ảnh.
MultipartBody.Part filePart = MultipartBody.Part.createFormData("hinh_anh", file.getName(), requestBody);
Log.d(TAG, "uploadFile: "+ filePart.body().toString());
Gson gson = new GsonBuilder().setLenient().create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
ApiService apiService = retrofit.create(ApiService.class);
Call<KetQuaUpload> objCall = apiService.uploadFile(filePart);
objCall.enqueue(new Callback<KetQuaUpload>() {
@Override
public void onResponse(Call<KetQuaUpload> call, Response<KetQuaUpload> response) {
Log.d(TAG, "onResponse: " + response.body());
if (response.isSuccessful()) {
// Upload thành công
Log.d(TAG, "onResponse: " + response.body().toString());
KetQuaUpload objKQ = response.body();
if(objKQ.error == null){
// không có lỗi, hien thi anh
Picasso.get().load(objKQ.link_anh).into(img_preview);
}
} else {
// Upload thất bại
}
}
@Override
public void onFailure(Call<KetQuaUpload> call, Throwable throwable) {
throwable.printStackTrace();
}
});
}
private String getRealPathFromURI(Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
Log.d(TAG, "getRealPathFromURI: " + cursor.getCount());
if (cursor != null) {
cursor.moveToFirst();
for(int i = 0; i< cursor.getColumnCount(); i++){
Log.d(TAG, "getRealPathFromURI: " + cursor.getColumnName(i) + "==>" + cursor.getString(i));
}
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
String path = cursor.getString(columnIndex);
cursor.close();
return path;
} else {
return null;
}
}
}