How to upload profile pic of a user using MULTIPART/FORM-DATA?

…衆ロ難τιáo~ 提交于 2019-12-11 15:30:54

问题


I'm trying to upload an image (which is selected from mobile ) using MULTIPART/FORM-DATAg and couldn't figure it out as I'm a newbie to Multipart. The data that is to be Uploaded are the image(NOT AS BASE64CODE) and user id.


回答1:


Here is the solution for uploading Image using Multipart

Add this file to dependencies

//For multipart

implementation 'com.karumi:dexter:5.0.0'

Now in Activity class, declare this 2 field

private RequestQueue rQueue;
Uri file_uri_1;

Next step is download file or copy code from link

Now Create a function to upload your Imageview

private void uploadImage() {

    ProgressDialog dialog = new ProgressDialog(getActivity());
    dialog.setCancelable(false);
    dialog.setMessage("Please wait...");
    dialog.show();

    MultipartRequest volleyMultipartRequest = new MultipartRequest(Request.Method.POST, <URL API URL>,
            new Response.Listener<NetworkResponse>() {
                @Override
                public void onResponse(NetworkResponse response) {

                    dialog.dismiss();
                    rQueue.getCache().clear();
                    try {
                        JSONObject jsonObject = new JSONObject(new String(response.data));
                            <GET YOUR RESPONSE FROM SEVER HERE>
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    dialog.dismiss();
                    Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }) {

        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            // Add parameter if you wish send extra parameters with Image
            params.put("<KEY>", <VALUE>);
            return params;
        }


        @Override
        protected Map<String, DataPart> getByteData() {
            Map<String, DataPart> params = new HashMap<>();
            // Check your file name or path is Empty or not
            if (fileName != null && !fileName.equalsIgnoreCase("")) {
                File file = new File(filePath);
                file_uri_1 = Uri.fromFile(file);
                params.put("<IMAGE KEY>", new DataPart(fileName, getFileDataFromDrawable(getActivity(), file_uri_1), getFileType(file_uri_1)));
            }

            return params;
        }
    };


    volleyMultipartRequest.setRetryPolicy(new DefaultRetryPolicy(0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    rQueue = Volley.newRequestQueue(getActivity());
    rQueue.add(volleyMultipartRequest);
}


public static byte[] getFileDataFromDrawable(Context context, Uri uri) {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    try {
        InputStream iStream = context.getContentResolver().openInputStream(uri);
        int bufferSize = 2048;
        byte[] buffer = new byte[bufferSize];

        // we need to know how may bytes were read to write them to the byteBuffer
        int len = 0;
        if (iStream != null) {
            while ((len = iStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, len);
            }
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    //  bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
    return byteArrayOutputStream.toByteArray();
}

Hope this code will help you.




回答2:


Try this, when you get file path on

onActivityResult

Add this code

String fileName = filePath.substring(filePath.lastIndexOf('/') + 1, filePath.length());
String ext = fileName.substring(fileName.lastIndexOf("."));

if ((ext.equalsIgnoreCase(".jpg"))
    || (ext.equalsIgnoreCase(".jpeg"))
    || (ext.equalsIgnoreCase(".png"))) {
    // Call method to upload your image 
} else {
    // Show alert to select Image with above extension
}

Hope this will help you.



来源:https://stackoverflow.com/questions/56406730/how-to-upload-profile-pic-of-a-user-using-multipart-form-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!