Android(Java)如何使用Retrofit从相机或画廊上传图像?

时间:2019-10-15 06:51:23

标签: android image server upload retrofit

我已经尝试了很多,以便使用android(Java)的改造功能将选择“相机或图库”之类的图像上传到服务器?

我曾在下面的源代码中尝试过此方法,但每次在其textup侦听器上上传图像时,其改造API都调用onFailure方法。

//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();
            }
        });
}

上面的代码中没有错误,但是每次点击改造API进行图片上传后,每次调用onFailure方法。

如果有人已经完成此任务,请回复!

感谢与问候, Android开发人员

0 个答案:

没有答案