Как загрузить несколько изображений, используя несколько частей в Volley в Android - PullRequest
0 голосов
/ 04 мая 2018

Я хочу загрузить несколько изображений на сервер, используя несколько частей, я не получил правильный код, кто-нибудь, пожалуйста, помогите мне решить мою проблему. Если я отправляю в формате base64, бэкэнд-команда не может получить мое изображение. Вот почему я иду с multipart. Залп или Асинктаск.

Я попробовал этот код по этой ссылке

https://www.simplifiedcoding.net/upload-image-to-server/

Но несколько изображений я не знаю, как сделать.

Main.Java

package com.getspot.getspot.imagerestapi;

public class MainActivity extends AppCompatActivity {


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

        findViewById(R.id.buttonUploadImage).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//if everything is ok we will open image chooser
                Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, 100);

}
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == RESULT_OK && data != null) {

            //getting the image Uri
            Uri imageUri = data.getData();
            try {
                //getting bitmap object from uri
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);

                //displaying selected image to imageview
                imageView.setImageBitmap(bitmap);

                //calling the method uploadBitmap to upload image
                uploadBitmap(bitmap);
               } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public byte[] getFileDataFromDrawable(Bitmap bitmap) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 80, byteArrayOutputStream);
        Log.i("AS","--"+byteArrayOutputStream.toByteArray());
        return byteArrayOutputStream.toByteArray();
    }

    private void uploadBitmap(final Bitmap bitmap) {

        //getting the tag from the edittext
        final String tags = editTextTags.getText().toString().trim();

        //our custom volley request
        VolleyMultipartRequest volleyMultipartRequest = new VolleyMultipartRequest(Request.Method.POST, ServerUtils.Gs_Clock_Image,
                new Response.Listener<NetworkResponse>() {
                    @Override
                    public void onResponse(NetworkResponse response) {
                        try {
                            JSONObject obj = new JSONObject(new String(response.data));

                            Log.i("AS","obj--"+obj);

                            Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.i("AS","error--"+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<>();
          params.put("gs_userId", "6");
                return params;
            }

            /*
            * Here we are passing image by renaming it with a unique name
            * */
            @Override
            protected Map<String, DataPart> getByteData() {
                Map<String, DataPart> params = new HashMap<>();
                long imagename = System.currentTimeMillis();
                Log.i("AS","imagename--"+imagename);

                Log.i("AS","getFileDataFromDrawable(bitmap)--"+getFileDataFromDrawable(bitmap));

                params.put("gs_task_image", new DataPart(imagename + ".png", getFileDataFromDrawable(bitmap)));
                return params;
            }
        };

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

}

Примечание: при передаче байтового массива в gs_text_image, как я могу отправить несколько изображений. Я ссылался на эту ссылку выше. Пожалуйста, помогите мне

1 Ответ

0 голосов
/ 04 мая 2018

Я покажу вам, как я это делаю (частный случай ofc, но это может дать вам представление)

Итак, прежде всего вам нужен интерфейс метода, который будет выглядеть так:

@Multipart
@POST(RestClient.UPLOAD_PICTURES_FOR_ORDER)
Call<YourTypeOfResponse> uploadPictures(@Part("images[]") RequestBody[] file, @Part MultipartBody.Part[] images);

Теперь вам нужно будет подготовить файлы (изображения), которые у вас есть, для запроса

private void multiparts(){
    RequestBody reqFullPicFile;
    MultipartBody.Part filepart;
    RequestBody filename;

    images = new MultipartBody.Part[files.size()];
    filenameImages = new RequestBody[files.size()];

    for (int file = 0; file < files.size(); file++){
        reqFullPicFile = RequestBody.create(MediaType.parse("multipart/form-data"), files.get(file));
        filepart = MultipartBody.Part.createFormData("full_picture", files.get(file).getName(), reqFullPicFile);
        filename = RequestBody.create(MediaType.parse("text/plain"), files.get(file).getName());
        images[file] = filepart;
        filenameImages[file] = filename;
    }
}

И, в конце концов, сделайте запрос с созданным Multiparts (в данном случае images & filenameImages)

private void uploadPicturesReq(){
    if (files != null) {
        multiparts();

        RestClient.getApi().uploadPictures(filenameImages, images)
                .enqueue(new Callback<PicturesResponse>() {
                    @Override
                    public void onResponse(Call<PicturesResponse> call, Response<PicturesResponse> response) {
                        if (response.isSuccessful() && response.code() == 200) {
                             // here you can handle the response from server
                        }
                    }

                    @Override
                    public void onFailure(Call<PicturesResponse> call, Throwable t) {
                        Log.e(TAG, "-=onFailure=- " + t.getMessage(), t);
                    }
                });
    }
}
...