Java Volley请求包含图像数据的多部分表单

时间:2020-09-11 06:40:24

标签: java android-studio android-volley multipartform-data

我正在尝试使用REST API将数据上传到我的Web应用程序。我需要发送带有其他参数的图像作为多部分数据。根据我在这里查看的一些帖子,我有以下方法。提交请求后,它失败了,并且从服务器日志中看起来好像没有在读取参数,并且ID失败了。

我对如何使用Volley构造请求感到困惑。如果我按如下所示使用失眠症发送了等效信息,则说明成功。我已经使用相同的承载令牌进行了复制。

enter image description here

private void uploadPicture() {
    progressDialog = new ProgressDialog(CameraActivity.this);
    progressDialog.setMessage("Uploading, please wait...");
    progressDialog.show();

    Log.d("URL", URL + PICNS);

    //converting image to base64 string
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Bitmap compressedImg = getResizedBitmap(imageBitmap,600);
    compressedImg.compress(Bitmap.CompressFormat.PNG, 100, baos);
    byte[] imageBytes = baos.toByteArray();
    final String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);

    Log.d("TOKEN", token);

    //sending image to server
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST,URL + PICNS,null, new Response.Listener<JSONObject>(){
        @Override
        public void onResponse(JSONObject response) {
            progressDialog.dismiss();
            Log.d("RESPONSE", response.toString());
        }

    },new Response.ErrorListener(){
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            Log.d("Error", volleyError.toString());
            Toast.makeText(CameraActivity.this, "Some error occurred -> "+volleyError, Toast.LENGTH_LONG).show();;
        }
    }) {
        //adding parameters to send
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> parameters = new HashMap<String, String>();
            parameters.put("route_id","1");
            parameters.put("lat","52.395728");
            parameters.put("lng","-1.992031");
            parameters.put("description", " ");
            parameters.put("caption", "Wow Uploaded This");
            parameters.put("picture", imageString);
            return parameters;
        }

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", "Bearer " + token);
            return headers;
        }


    };

    RequestQueue rQueue = Volley.newRequestQueue(CameraActivity.this);
    rQueue.add(request);
}

1 个答案:

答案 0 :(得分:0)

我使用了here中的库来发送多部分请求,它似乎对我有用。