Загрузка изображения на сервер залпом с данными из нескольких частей в теле почтового запроса - PullRequest
1 голос
/ 24 июня 2019

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

   private void uploadBitmap(final Bitmap bitmap) throws JSONException {

    //our custom volley request
    String URL = "https://<---------->/me/avatar";

    JSONObject jsonBody = new JSONObject();

    jsonBody.put("avatar", new VolleyMultipartRequest.DataPart( "index.png", getFileDataFromDrawable(bitmap)));
    final String requestBody = jsonBody.toString();
    VolleyMultipartRequest volleyMultipartRequest = new VolleyMultipartRequest(Request.Method.POST, URL,
            new Response.Listener<NetworkResponse>() {
                @Override
                public void onResponse(NetworkResponse response) {
                    loading.setVisibility(View.GONE);
                    Toast.makeText(ProfileSettings.this, "Image uploaded successfully", Toast.LENGTH_SHORT).show();
                    try {
                        JSONObject obj = new JSONObject(new String(response.data));

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    loading.setVisibility(View.GONE);
                    Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }) {


        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> params = new HashMap<String, String>();
            params.put("Content-Type", "application/json; charset=UTF-8");
            params.put("Authorization", "Bearer " + jsonToken);
            return params;
        }

        @Override
        protected Map<String, DataPart> getByteData() {
            Map<String, DataPart> params = new HashMap<>();
            long imagename = System.currentTimeMillis();
            params.put("avatar", new DataPart(imagename + ".png", getFileDataFromDrawable(bitmap)));
            return params;
        }

        @Override
        public byte[] getBody() throws AuthFailureError {
            return requestBody.getBytes();
        }
    };

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

Я получил этот код из учебных пособий, но они дают ошибку 500, так что я думаю, это может быть потому, что мне нужно передать «avatar»: «index.png» в теле запроса, а не таким образом.

Ответы [ 2 ]

0 голосов
/ 30 июня 2019

Я смог добиться этого, используя модификацию 2, вот код.

@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
            logo.setImageBitmap(bitmap);

            //calling the method uploadBitmap to upload image
            loading.setVisibility(View.VISIBLE);
            ///uploadBitmap(bitmap);

            File file = new File(getRealPathFromUri(this, imageUri));
            uploadImageFile(file);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public static String getRealPathFromUri(Context context, Uri contentUri) {
    Cursor cursor = null;
    try {
        String[] proj = { MediaStore.Images.Media.DATA };
        cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

private void uploadImageFile(File file) throws IOException {

    file  = new Compressor(this).compressToFile(file);
    RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);
    // MultipartBody.Part is used to send also the actual filename
    MultipartBody.Part body = MultipartBody.Part.createFormData("avatar", file.getName(), requestFile);

    ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);
    Call<ServerResponse> call = getResponse.uploadFile("Bearer "+jsonToken, body);
    call.enqueue(new Callback< ServerResponse >() {
        @Override
        public void onResponse(@NonNull Call < ServerResponse > call, @NonNull retrofit2.Response<ServerResponse> response) {
            ServerResponse serverResponse = response.body();

            if (serverResponse.getData() != null) {
                Log.e(TAG, "Response is "+ serverResponse.getData());
               loading.setVisibility(View.GONE);
                Toast.makeText(ProfileSettings.this, "Avatar updated", Toast.LENGTH_SHORT).show();
            } else {
                Log.e("Response", String.valueOf(serverResponse));
            }
        }


        @Override
        public void onFailure(Call < ServerResponse > call, Throwable t) {
            Log.e(TAG, t.getMessage());
        }
    });
       // Log.e(TAG, "request is "+call.request().body()+" and "+call.request().headers());
    }
0 голосов
/ 24 июня 2019

перейдите по этой ссылке - https://www.simplifiedcoding.net/upload-image-to-server/ https://www.simplifiedcoding.net/android-upload-image-to-server/

, а также используйте эту библиотеку для загрузки изображения и файла - https://github.com/gotev/android-upload-service.

.библиотеки.

...