如何在Android中使用Volley进行多部分/表单数据请求?

I am developing an Android app. Now , I am having a problem with file upload. I have a function in backend that create item with image. I am using repository pattern, so I can share functions to API. Before I am uploading file in this way.

My activity for file upload:

public class CreateItemActivity extends Activity {
    Button btnChose;
    Button btnUpload;
    Bitmap bitmap;
    ImageView imageView;
    private String KEY_IMAGE = "image";
    private String KEY_NAME = "name";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create_item);
        btnChose = (Button)findViewById(R.id.buttonChoose);
        btnUpload = (Button)findViewById(R.id.buttonUpload);
        btnChose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showFileChooser();
            }
        });
        imageView = (ImageView)findViewById(R.id.imageView);
        btnUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uploadImage();
            }
        });
    }

    private void showFileChooser()
    {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Choose image"), 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
            Uri filePath = data.getData();
            try {
                //Getting the Bitmap from Gallery
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                //Setting the Bitmap to ImageView
                imageView.setImageBitmap(bitmap);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public String getStringImage(Bitmap bmp){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] imageBytes = baos.toByteArray();
        String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
        return encodedImage;
    }

    private void uploadImage(){
        //Showing the progress dialog
        final ProgressDialog loading = ProgressDialog.show(this,"Uploading...","Please wait...",false,false);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, getResources().getString(R.string.api_end_point)+"android-upload",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        //Disimissing the progress dialog
                        loading.dismiss();
                        //Showing toast message of the response
                        Toast.makeText(getBaseContext(), "File uploaded" , Toast.LENGTH_LONG).show();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        //Dismissing the progress dialog
                        loading.dismiss();

                        //Showing toast
                       Toast.makeText(getBaseContext(), "Error listener", Toast.LENGTH_LONG).show();
                    }
                }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                //Converting Bitmap to String
                String image = getStringImage(bitmap);

                //Getting Image Name
                String name = "android_uploaded_image";

                //Creating parameters
                Map<String,String> params = new Hashtable<String, String>();

                //Adding parameters
                params.put(KEY_IMAGE, image);
                params.put(KEY_NAME, name);

                //returning parameters
                return params;
            }
        };

        //Creating a Request Queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);

        //Adding request to the queue
        requestQueue.add(stringRequest);
    }
}'

That is just test activity for file upload. It works fine. It uploads file to server. But the problem is I have to upload file in server like below. I am using PHP for backend.

<?php file_put_contents(time().".png", base64_decode($_POST['image']); ?>

As you can see above, I cannot retrieve file like $_FILES['image']. Instead, I have to use $_POST. My problem is I already have function for file upload in server that uses $_FILES. So I am trying to make multipart/form-data request. I searched articles for it. But these are incomplete because some components in code cannot be used.

For example, for this link Trouble Sending Multipart File with Boundary via Volley, I cannot use MultipartBuilder. How can I make multipart/form-data request easily using volley in android. I am using latest API version , so some functions and components cannot be used as in link I mentioned.

douzhao7445
douzhao7445 不,我还在寻找它。我找不到完美而完整的代码。现在,我只是将文件压缩为字节串来上传。但我觉得,这对我的应用来说还不够好。如果你发现它,请告诉我。谢谢。@LucasBrito
4 年多之前 回复
dongqiang8683
dongqiang8683 同样的问题。您是否发现任何使用排球上传为$_FILES的解决方案?
4 年多之前 回复
dpvhv66448
dpvhv66448 如果你想要MultipartEntityBuilder,你可以在stackoverflow.com/questions/16797468/...阅读我的答案和其他人。
4 年多之前 回复
duanao6704
duanao6704 请问MultipartEntityBuilder怎么样?
4 年多之前 回复
doumei4964
doumei4964 你可以使用PhotoMultipartRequest:gist.github.com/mbarcia/8660924
4 年多之前 回复
dpjjr42626
dpjjr42626 请阅读stackoverflow.com/questions/32240177/...以了解它是否可以帮助您
4 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐