Android (Java), как загрузить изображение с камеры или галереи с помощью Retrofit? - PullRequest
0 голосов
/ 15 октября 2019

Я много пробовал, чтобы загрузить изображение, выбирая такие опции, как «Камера или Галерея», на сервер, используя модификацию в Android (Java)?

Я пробовал этот код ниже, но каждый разего модифицированный API вызывает метод onFailure при загрузке изображения в прослушиватели щелчков textView.

//BASE_URL

public static final String BASE_URL = "https://YOUR_BASE_UL";


@Multipart
@PUT(ApiClient.SubUrls.UPLOADIMAGE)
Call<ResponseBody> uploadImageToServer(customized parametters,...,  MultipartBody.Part imageFile);

@OnClick(R.id.tvEdit)
    void openForPicture(View view)
    {
        if (TextUtils.isEmpty(image_name))
        {
            if (isNetworkConnected())
            {
                selectPicture();
            }
            else
            {
                Toast.makeText(mContext, R.string.string_internet_connection_warning, Toast.LENGTH_LONG).show();
            }
        }
        else
        {
            Toast.makeText(mContext, R.string.string_message_to_attach_file, Toast.LENGTH_SHORT).show();
        }
    }


    private void selectPicture()
    {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
        {
            tvEdit.setEnabled(true);
            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.CAMERA,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
        }

        final CharSequence[] items = {"Camera", "Gallery", "Cancel"};
        AlertDialog.Builder builder = new AlertDialog.Builder(PersonalInfoActivity.this);
        builder.setTitle("Add Image");
        builder.setItems(items, new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                if (items[which].equals("Camera"))
                {
                    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(cameraIntent, REQUEST_CAMERA);

                    /*Intent intentCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(intentCamera, REQUEST_CAMERA);*/
                }
                else if (items[which].equals("Gallery"))
                {
                    Intent intentGallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intentGallery.setType("image/*");
                    startActivityForResult(intentGallery.createChooser(intentGallery, "Select File"), SELECT_FILE);
                }
                else if (items[which].equals("Cancel"))
                {
                    dialog.dismiss();
                }
            }
        });

        builder.show();
    }


@Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data)
    {


        if (resultCode == Activity.RESULT_OK)
        {
            if (requestCode == REQUEST_CAMERA)
            {
                assert data != null;
                Bundle bundle = data.getExtras();
                assert bundle != null;
                final Bitmap bitmap = (Bitmap) bundle.get("data");
                ivProfileImage.setImageBitmap(bitmap);
                selectedImageUri = data.getData();
                ivProfileImage.setImageURI(selectedImageUri);

            }
            else if (requestCode == SELECT_FILE)
            {
                assert data != null;
                selectedImageUri = data.getData();
                ivProfileImage.setImageURI(selectedImageUri);

            }
        }

        super.onActivityResult(requestCode, resultCode, data);
        sendProfilePicToServer();

    }

    private void sendProfilePicToServer()
    {
        /**------------------------------*/

        SweetAlertDialog pDialog = new SweetAlertDialog(PersonalInfoActivity.this, SweetAlertDialog.PROGRESS_TYPE);
        pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
        pDialog.setTitleText("Loading ...");
        pDialog.setCancelable(true);
        pDialog.show();

        //Create Upload Server Client
        ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);

        //File creating from selected URL
        File file1 = new File(getDataDir().getAbsolutePath());

        // create RequestBody instance from file
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file1);

        // MultipartBody.Part is used to send also the actual file name
        MultipartBody.Part body = MultipartBody.Part.createFormData(ApiClient.SubUrls.UPLOADIMAGE, file1.getName(), requestFile);

        File file = new File(getImagePath(selectedImageUri));

        RequestBody requestBody = RequestBody.create(MediaType.parse(getContentResolver().getType(fileUri)), file);

        MultipartBody.Part multipartBody = MultipartBody.Part.createFormData("", file.getName(),requestBody);

        // finally, execute the request
        Call<ResponseBody> call = apiInterface.uploadImageToServer(sharePref.getToken(), sharePref.getUserId(), sharePref.getId(), body);

        call.enqueue(new Callback<ResponseBody>()
        {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response)
            {
                pDialog.dismissWithAnimation();

                if (response.isSuccessful())
                {
                    assert response.body() != null;
                    if (response.body().equals("success"))
                    {
                        Log.e("onResponse--> ", "" + response.body());
                        Toast.makeText(PersonalInfoActivity.this, "onResponse-->ProfilePicUpload" + response.message(), Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t)
            {
                Log.e("onFailure-->", t.getLocalizedMessage());
                Toast.makeText(PersonalInfoActivity.this, "onFailure-->ProfilePicUpload" + t.getMessage(), Toast.LENGTH_SHORT).show();
                pDialog.dismissWithAnimation();
            }
        });
}

В приведенном выше коде нет ошибки, но каждый раз, когда метод onFailure вызывается после нажатия на модифицированный API для изображениязагрузить.

Пожалуйста, ответьте, если кто-нибудь уже выполнил это задание!

Спасибо и С уважением, Разработчик Android

...