在Volley Request中将图像与其他参数作为多部分发送 [英] Send Images as Multipart with Other Params in Volley Request

查看:143
本文介绍了在Volley Request中将图像与其他参数作为多部分发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用截击请求向服务器发送一个带有两个参数的请求,并且工作正常.现在,要求已更改,我需要将至少一个图像或最多3个图像以及其他两个参数发送到服务器.图像必须作为多部分发送.我有以下代码用于从图库中获取图像并将其文件路径存储在列表中.

I was sending a request to the server with two parameters using volley request and it was working fine. Now the requirement has changed and I need to send at least one image or maximum 3 images to the server along with the other two parameters. The image must be sent as multi-part. I have following code for Getting image from gallery and storing their file paths in the list.

List<String> imagePathList = imageFilePaths;
List<MultipartBody.Part> partMap = new ArrayList<>();
for (int i = 0; i < imagePathList.size(); i++) {
    Uri fileUri = Uri.parse(imagePathList.get(i));
    RequestBody requestFile = RequestBody.create(
            MediaType.parse(getMimeTypee(FileUtils.getFile(getContext(), fileUri).getAbsolutePath())),
            FileUtils.getFile(getContext(), fileUri)
    );

   MultipartBody.Part body = MultipartBody.Part.createFormData("court_image[" + i + "]", FileUtils.getFile(getContext(), fileUri).getName(), requestFile);
   partMap.add(body);
}

imageFilePathsArrayList的位置.服务器将接收court_image[0]court_image[1]等图像,具体取决于我在ArrayList中具有多少图像路径.

Where imageFilePaths is an ArrayList. The server will receive images like court_image[0], court_image[1] and so on, depends on how many image paths I have in ArrayList.

齐射要求在这里

RequestQueue queue = Volley.newRequestQueue(getContext());
StringRequest postRequest = new StringRequest(Request.Method.POST, url1,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Toast.makeText(mBaseAppCompatActivity, "Success", Toast.LENGTH_SHORT).show();
           }
        },
        new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }
) {

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> params = new HashMap<String, String>();
        String token = getToken();
        params.put("Authorization", "Bearer " + token);
        params.put("Content-Type", "multipart/form-data");
        return params;
    }

    @Override
    protected Map<String, String> getParams() {
        Map<String, String> params = new HashMap<String, String>();
        params.put("terms", "true");
        params.put("phone", "phoneNo");
        return params;
    }

};
queue.add(postRequest);

现在事情变得很复杂了,我可以从图库中获取图像并将其路径存储在ArrayList中,但是我不知道如何通过多部分排球请求中的零件数据.请帮忙.

Now the thing is as I am new to the multi-part thing, with the help I am able to get the image from gallery and storing their path in ArrayList but I don't know how to pass the multi-part data in this volley request. Please help.

推荐答案

尽管这是一个老问题,但我认为我应该在此处发布答案,因为我遇到了同样的问题,可以设法解决.

Though this is an old question, I thought I should post my answer here as I was having the same problem and could manage to solve that.

为了上载图像以及其他一些参数,我使用了齐射.但是,我发现了原始齐射库的包装器,该包装器更易于集成到多部分请求中.因此,我在build.gradle文件中添加了以下库.

For uploading the image along with some other parameters, I used volley. However, I found a wrapper of the original volley library which is easier to integrate for multi-part requests. Hence I added the following library in the build.gradle file.

dependencies {
    compile 'dev.dworks.libs:volleyplus:+'
}

我从build.gradle 中删除了原始的凌空库,并改用了上述库,该库可以处理具有类似集成技术的多部分请求和常规请求.

I removed the original volley library from my build.gradle and used the above library instead which can handle both multi-part and normal requests having similar integration technique.

然后,我只需要编写下面的类来处理POST请求操作.

Then I just had to write the following class which handles the POST request operation.

public class POSTMediasTask {
    public void uploadMedia(final Context context, String filePath) {

        String url = getUrlForPOSTMedia(); // This is a dummy function which returns the POST url for you
        SimpleMultiPartRequest multiPartRequestWithParams = new SimpleMultiPartRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d("Response", response);
                        // TODO: Do something on success
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // TODO: Handle your error here
            }
        });

        // Add the file here
        multiPartRequestWithParams.addFile("file", filePath);

        // Add the params here
        multiPartRequestWithParams.addStringParam("terms", "SomeTerms");
        multiPartRequestWithParams.addStringParam("phone", "85050055055");

        RequestQueue queue = Volley.newRequestQueue(context);
        queue.add(multiPartRequestWithParams);
    }
}

现在执行如下任务.

new POSTMediasTask().uploadMedia(context, mediaPath);

您可以使用此库一次上传一个文件.但是,我可以通过启动多个任务来设法上传多个文件.

You can upload one file at a time using this library. However, I could manage to upload multiple files, just by initiating multiple tasks.

希望有帮助!

这篇关于在Volley Request中将图像与其他参数作为多部分发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆