如何在Android中使用Volley中的多部分上传多个图像

时间:2018-05-04 07:42:25

标签: android android-asynctask android-volley multipart

我想使用多部分将多个图像上传到服务器,我没有得到正确的代码,有人请帮我修复解决我的问题。如果我发送为base64格式,后端团队无法获取我的图像。多数民众赞成我为什么选择多部分。无论是Volley还是Asynctask。

我在此链接中尝试了此代码

  

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 :(得分:0)

我会告诉你我是怎么做的(特殊情况是c,但它可能会给你一个想法)

所以,首先你需要方法接口,如下所示:

@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);
                    }
                });
    }
}