Отправка одного изображения несколько раз - PullRequest
0 голосов
/ 26 апреля 2018

Я работаю над приложением обмена изображениями. Я могу загрузить изображение на сервер, но оно загружает одно и то же изображение несколько раз (3-4 раза).

У меня есть фрагмент изображения, где я дал плавающие кнопки для выбора камеры или галереи.

Фрагмент изображения

@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.fragment_images, container, false);

    floatcamera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            File imageFolder = new File(Environment.getExternalStorageDirectory(), "/My Children");
            imageFolder.mkdir();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyymmdd_hhmmss");
            String timestamp = simpleDateFormat.format(new Date());
            File image = new File(imageFolder, timestamp+ ".jpg");
            //    Uri uriImage = Uri.fromFile(image);
            camerauri = FileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID +  ".provider", image);
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, camerauri);
            startActivityForResult(intent, TAKE_PICTURE);
        }
    });
    floatgallery.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(intent, SELECT_PICTURE);
        }
    });

    return v;

}

  @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    try {
        if (requestCode == TAKE_PICTURE ) {
            Intent i = new Intent(getContext(), Upload.class);
            i.putExtra("image", camerauri.toString());
            startActivity(i);
        }
        if (requestCode == SELECT_PICTURE) {
            Intent i = new Intent(getContext() , Upload.class);
            i.putExtra("image", data.getData().toString());
            startActivity(i);
        }
    }catch (Exception e){
        e.printStackTrace();
    }
}

После щелчка или выбора изображения результирующее одиночное изображение отображается в следующей операции. И есть кнопка для загрузки. Я использую Custom Volley Request, так как Volley не поддерживает Multipart.

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

    ImageView imageview = (ImageView) findViewById(R.id.imageview);
    Intent intent = getIntent();
    if (intent == null){
        return;
    }
    final Uri imageUri = Uri.parse(intent.getStringExtra("image"));
   try {
        bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),imageUri);
    } catch (IOException e) {
        e.printStackTrace();
    }

Glide
        .with(this)
        .load(imageUri)
        .apply(new RequestOptions().priority(Priority.HIGH).fitCenter().diskCacheStrategy(DiskCacheStrategy.ALL))
        .into(imageview);
    progressDialog = new ProgressDialog(Upload.this);
    progressDialog.setMessage("Uploading");

    btnUpload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            caption = txtCaption.getText().toString();
            uploadBitmap(bitmap);

        }
    });
 }

  public byte[] getFileDataFromDrawable(Bitmap bitmap) {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 70, byteArrayOutputStream);
    return byteArrayOutputStream.toByteArray();
}
private void uploadBitmap(final Bitmap bitmap) {

progressDialog.show();
    //our custom volley request
    MultipartRequest volleyMultipartRequest = new MultipartRequest(Request.Method.POST, IMAGE_UPLOAD_URL,
            new Response.Listener<NetworkResponse>() {
                @Override
                public void onResponse(NetworkResponse response) {
                        progressDialog.dismiss();
                        Toast.makeText(Upload.this, "Image Uploaded", Toast.LENGTH_SHORT).show();
                        progressDialog.dismiss();
                        finish();

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }) {

        /*
         * If you want to add more parameters with the image
         * you can do it here
         * here we have only one parameter with the image
         * which is tags
         * */
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            userid = SharedPreferenceManager.getmInstance(Upload.this).getMobileno();
            params.put("userid", userid);
            params.put("caption", caption);
            params.put("product","normal");
            return params;
        }

        /*
         * Here we are passing image by renaming it with a unique name
         * */
        @Override
        protected Map<String, MultipartRequest.DataPart> getByteData() {
            Map<String, MultipartRequest.DataPart> params = new HashMap<>();
            long imagename = System.currentTimeMillis();
            params.put("uploadedfile", new MultipartRequest.DataPart(imagename + ".jpeg", getFileDataFromDrawable(bitmap)));
            return params;
        }
    };

    //adding the request to volley
    Volley.newRequestQueue(this).add(volleyMultipartRequest);
}

1 Ответ

0 голосов
/ 26 апреля 2018

Надеюсь, это сработает для вас

переопределить таким образом

 @Override
    protected Map<String, MultipartRequest.DataPart> getByteData() {
        Map<String, MultipartRequest.DataPart> params = new HashMap<>();
        String imagename = imageUri.getLastPathSegment();
        params.put("uploadedfile", new MultipartRequest.DataPart(imagename,getFileDataFromDrawable(bitmap)));
        return params;
    }
...