Код вашей активности
public class ImageActivity extends Activity implements View.OnClickListener {
public static final int MEDIA_TYPE_IMAGE = 1;
public static final String IMAGE_DIRECTORY_NAME = "Android File Upload";
private static final int REQUEST_TAKE_PHOTO = 0;
private static final int REQUEST_PICK_PHOTO = 2;
private static final int CAMERA_PIC_REQUEST = 1111;
private static final String TAG = ImageActivity.class.getSimpleName();
private static final int PERMISSION_REQUEST_CODE = 1;
ImageView imageView;
Button pickImage, upload;
ProgressDialog pDialog;
private Uri fileUri;
private String mediaPath;
private String mImageFileLocation = "";
private String postPath;
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(TAG, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + ".jpg");
} else {
return null;
}
return mediaFile;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image_layout);
imageView = (ImageView) findViewById(R.id.preview);
pickImage = (Button) findViewById(R.id.pickImage);
upload = (Button) findViewById(R.id.upload);
pickImage.setOnClickListener(this);
upload.setOnClickListener(this);
initDialog();
}
@TargetApi(Build.VERSION_CODES.M)
@Override
public void onClick(final View v) {
switch (v.getId()) {
case R.id.pickImage:
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Log.v(TAG, "Permission is granted");
//File write logic here
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, REQUEST_PICK_PHOTO);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
break;
case R.id.upload:
uploadFile();
break;
}
}
private boolean isExternalStorageAvailable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
} else {
return false;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.v(TAG, "Permission: " + permissions[0] + "was " + grantResults[0]);
//resume tasks needing this permission
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_TAKE_PHOTO || requestCode == REQUEST_PICK_PHOTO) {
if (data != null) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
assert cursor != null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
mediaPath = cursor.getString(columnIndex);
// Set the Image in ImageView for Previewing the Media
Bitmap bitmapImage = BitmapFactory.decodeFile(mediaPath);
bitmapImage = getResizedBitmap(bitmapImage, 400);// 400 is for example, replace with desired size
imageView.setImageBitmap(bitmapImage);
cursor.close();
postPath = mediaPath;
}
} else if (requestCode == CAMERA_PIC_REQUEST) {
if (Build.VERSION.SDK_INT > 21) {
Glide.with(this).load(mImageFileLocation).into(imageView);
postPath = mImageFileLocation;
} else {
Glide.with(this).load(fileUri).into(imageView);
postPath = fileUri.getPath();
}
}
} else if (resultCode != RESULT_CANCELED) {
Toast.makeText(this, "Sorry, there was an error!", Toast.LENGTH_LONG).show();
}
}
/**
* Checking device has camera hardware or not
*/
private boolean isDeviceSupportCamera() {
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
protected void initDialog() {
pDialog = new ProgressDialog(this);
pDialog.setMessage(getString(R.string.msg_loading));
pDialog.setCancelable(true);
}
protected void showpDialog() {
if (!pDialog.isShowing()) pDialog.show();
}
protected void hidepDialog() {
if (pDialog.isShowing()) pDialog.dismiss();
}
/**
* Launching camera app to capture image
*/
private void captureImage() {
if (Build.VERSION.SDK_INT > 21) { //use this if Lollipop_Mr1 (API 22) or above
Intent callCameraApplicationIntent = new Intent();
callCameraApplicationIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
// We give some instruction to the intent to save the image
File photoFile = null;
try {
// If the createImageFile will be successful, the photo file will have the address of the file
photoFile = createImageFile();
// Here we call the function that will try to catch the exception made by the throw function
} catch (IOException e) {
Logger.getAnonymousLogger().info("Exception error in generating the file");
e.printStackTrace();
}
// Here we add an extra file to the intent to put the address on to. For this purpose we use the FileProvider, declared in the AndroidManifest.
Uri outputUri = FileProvider.getUriForFile(
this,
BuildConfig.APPLICATION_ID + ".provider",
photoFile);
callCameraApplicationIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
// The following is a new line with a trying attempt
callCameraApplicationIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
Logger.getAnonymousLogger().info("Calling the camera App by intent");
// The following strings calls the camera app and wait for his file in return.
startActivityForResult(callCameraApplicationIntent, CAMERA_PIC_REQUEST);
} else {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
}
File createImageFile() throws IOException {
Logger.getAnonymousLogger().info("Generating the image - method started");
// Here we create a "non-collision file name", alternatively said, "an unique filename" using the "timeStamp" functionality
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmSS").format(new Date());
String imageFileName = "IMAGE_" + timeStamp;
// Here we specify the environment location and the exact path where we want to save the so-created file
File storageDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES + "/photo_saving_app");
Logger.getAnonymousLogger().info("Storage directory set");
// Then we create the storage directory if does not exists
if (!storageDirectory.exists()) storageDirectory.mkdir();
// Here we create the file using a prefix, a suffix and a directory
File image = new File(storageDirectory, imageFileName + ".jpg");
// File image = File.createTempFile(imageFileName, ".jpg", storageDirectory);
// Here the location is saved into the string mImageFileLocation
Logger.getAnonymousLogger().info("File name and path set");
mImageFileLocation = image.getAbsolutePath();
// fileUri = Uri.parse(mImageFileLocation);
// The file is returned to the previous intent across the camera application
return image;
}
/**
* Here we store the file url as it will be null after returning from camera
* app
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on screen orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
/**
* Receiving activity result method will be called after closing the camera
* */
/**
* ------------ Helper Methods ----------------------
*/
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
int width = image.getWidth();
int height = image.getHeight();
float bitmapRatio = (float) width / (float) height;
if (bitmapRatio > 1) {
width = maxSize;
height = (int) (width / bitmapRatio);
} else {
height = maxSize;
width = (int) (height * bitmapRatio);
}
return Bitmap.createScaledBitmap(image, width, height, true);
}
// Uploading Image/Video
private void uploadFile() {
if (postPath == null || postPath.equals("")) {
Toast.makeText(this, "please select an image ", Toast.LENGTH_LONG).show();
return;
} else {
showpDialog();
// Map is used to multipart the file using okhttp3.RequestBody
Map<String, RequestBody> map = new HashMap<>();
File file = new File(postPath);
// Parsing any Media type file
RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), file.getName());
ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);
Call<ServerResponse> call = getResponse.uploadFile(fileToUpload, filename);
call.enqueue(new Callback<ServerResponse>() {
@Override
public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
hidepDialog();
ServerResponse serverResponse = response.body();
Toast.makeText(getApplicationContext(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
} else {
hidepDialog();
Toast.makeText(getApplicationContext(), "problem uploading image", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<ServerResponse> call, Throwable t) {
hidepDialog();
Log.v("Response gotten is", t.getMessage());
}
});
}
}
}
==== Класс AppConfig ======= `
public class AppConfig {
private static String BASE_URL = "yourbase URL";
static Retrofit getRetrofit() {
return new Retrofit.Builder()
.baseUrl(AppConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
}
=======Interface Config===========
interface ApiConfig {
@Multipart
@POST("retrofit_example/upload_image.php")
Call<ServerResponse> uploadFile(@Part MultipartBody.Part file,
@Part("file") RequestBody name);
@Multipart
@POST("retrofit_example/upload_multiple_files.php")
Call<ServerResponse> uploadMulFile(@Part MultipartBody.Part file1,
@Part MultipartBody.Part file2);
}