Загрузить несколько изображений с помощью Android Volley - PullRequest
0 голосов
/ 24 мая 2018
private void imageBrowse() {
        Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST);
    }

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if(requestCode == PICK_IMAGE_REQUEST){
            Uri picUri = data.getData();
            FileUpload fileUpload = new FileUpload(getApplicationContext());
            filePath = fileUpload.getPath(picUri);
            image_preview1.setImageURI(picUri);
        }
    }
}

Может кто-нибудь помочь мне загрузить несколько изображений с помощью Volley Android

1 Ответ

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

Создайте RestApiMultiPartRequests.class

private class RestApiMultiPartRequests<T> extends Request<T> {

    private final Map<String, String> mStringParts;
    private final Map<String, File> mFileParts;
    private MultipartEntityBuilder mBuilder;
    private final Response.Listener<T> mListener;

    public RestApiMultiPartRequests(String url,
                                    Map<String, String> stringParts,
                                    Map<String, File> fileParts,
                                    Response.Listener<T> listener,
                                    Response.ErrorListener errorListener) {
        super(Method.POST, url, errorListener);
        mListener = listener;
        mStringParts = stringParts;
        mFileParts = fileParts;
        buildMultipartEntity();
    }

    private void buildMultipartEntity() {
        if (mBuilder != null) {
            mBuilder = null;
        }
        mBuilder = MultipartEntityBuilder.create();
        mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        mBuilder.setBoundary("_____" + Long.toString(System.currentTimeMillis()) + "_____");
        mBuilder.setCharset(Consts.UTF_8);
        if (mStringParts != null) {
            for (Map.Entry<String, String> entry : mStringParts.entrySet()) {
                mBuilder.addTextBody(entry.getKey(), entry.getValue(), ContentType.create("text/plain", Charset.forName("UTF-8")));
            }
        }

        Log.e("Size", "Size: " + mFileParts.size());
        for (Map.Entry<String, File> entry : mFileParts.entrySet()) {
            ContentType imageContentType = ContentType.create("image/*");//MULTIPART_FORM_DATA;
            Log.d("", "Key " + entry.getKey());
            Log.d("", "Value " + entry.getValue());
            Log.d("", "Name " + entry.getValue().getName());
            //"userfile"
            mBuilder.addBinaryBody(entry.getKey(), entry.getValue(), imageContentType, entry.getValue().getName());
        }
    }

    @Override
    public String getBodyContentType() {
        return mBuilder.build().getContentType().getValue();
    }

    @Override
    public byte[] getBody() {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            mBuilder.build().writeTo(bos);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return bos.toByteArray();
    }


    public HttpEntity getEntity() {
        return mBuilder.build();
    }


    @SuppressWarnings("unchecked")
    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            return (Response<T>) Response.success(jsonString, HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        }
    }

    @Override
    protected void deliverResponse(T response) {
        mListener.onResponse(response);

    }


}

и загрузите изображение, используя этот метод

 /**
 * Upload image
 */
private void UploadImage() {

    RestApiMultiPartRequests<String> restApiMultiPartRequest =
            new RestApiMultiPartRequests<String>(url, hashMap, fileparts, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.i(LOG_TAG, "URL " + url + "\n Response : " + response);
                    if (iRestApiListener != null) {
                        setparsing(response);
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // Handle your error types accordingly.For Timeout & No
                    // connection error, you can show 'retry' button.
                    // For AuthFailure, you can re login with user
                    // credentials.
                    // For ClientError, 400 & 401, Errors happening on
                    // client side when sending api request.
                    // In this case you can check how client is forming the
                    // api and debug accordingly.
                    // For ServerError 5xx, you can do retry or handle
                    // accordingly.
                    int errorCode;
                    if (error instanceof NetworkError) {
                        errorCode = NETWORK_ERROR;
                        Log.i(LOG_TAG, "NetworkError" + error);
                    } else if (error instanceof ServerError) {
                        errorCode = SERVER_ERROR;
                        Log.i(LOG_TAG, "ServerError" + error);
                    } else if (error instanceof AuthFailureError) {
                        errorCode = AUTH_FAILURE_ERROR;
                        Log.i(LOG_TAG, "AuthFailureError" + error);
                    } else if (error instanceof ParseError) {
                        errorCode = PARSE_ERROR;
                        Log.i(LOG_TAG, "ParseError" + error);
                    } else if (error instanceof NoConnectionError) {
                        errorCode = NO_CONNECTION_ERROR;
                        Log.i(LOG_TAG, "NoConnectionError" + error);
                    } else if (error instanceof TimeoutError) {
                        errorCode = TIME_OUT_ERROR;
                        Log.i(LOG_TAG, "TimeoutError" + error);
                    } else {
                        errorCode = UNKNOWN_ERROR;
                        Log.i(LOG_TAG, "TimeoutError" + error);
                    }

                    //Log.i(LOG_TAG,"StatusCode" + error.networkResponse.statusCode);
                    if (iRestApiListener != null) {
                        iRestApiListener.onCallFinish();
                        try {
                            iRestApiListener.onError(new JSONArray());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }) {

                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String> params = new HashMap<String, String>();
                    if (StringUtils.isNotEmpty(AppClass.preferences.getValueFromPreferance(Preferences.TOKEN))) {
                        params.put("Authorization", AppClass.preferences.getValueFromPreferance(Preferences.TOKEN));
                    }

                    return params;
                }

                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    Map<String, String> params = new HashMap<String, String>();
                    return params;
                }
            };

    restApiMultiPartRequest.setRetryPolicy(new DefaultRetryPolicy(0, 1, 2));//10000
    AppClass.mVolleyInstance.addToRequestQueue(restApiMultiPartRequest);
}

здесь fileparts равно HashMap<String,File>, так что вы можете создать такую ​​хеш-карту и добавить несколькофайл к нему, и этот единственный запрос может загрузить файл с несколькими изображениями на сервер

...