Sunday, 26 March 2017

Android: Upload images using MultipartPost request

An HTTP MultipartPost request is a request that HTTP clients construct to send files and data over to a HTTP Server. It is commonly used by browsers and HTTP clients to upload files to the server.

To implement this request in your android applications to send images to your server follow these simple steps.

1. Add the following dependency in your build.gradle file:

                     compile 'com.squareup.okhttp3:okhttp:3.2.0'    

2. Now just add the code snippet with following parameters described as follows:


void uploadImageThroughMultipartPostRequest(File yourFileToBeUploaded) {

// yourFileToBeUploaded is your image file
        String contentType = null;
        RequestBody fileBody = null;
        if (yourFileToBeUploaded != null) {
            try {
                contentType = yourFileToBeUploaded.toURL().openConnection().getContentType();
            } catch (Exception e) {
                e.printStackTrace();
            }
            fileBody = RequestBody.create(MediaType.parse(contentType), yourFileToBeUploaded);
        }
       
       String requestURL = "YOUR_POST_REQUEST_URL" ;
       
       RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM) // Type to set Form request
                .addFormDataPart("uploaded_file", yourFileToBeUploaded.getPath())
                .addFormDataPart("uploaded_file_tag", "File_Name.jpeg", fileBody)
                .build();

        Request request = new Builder()
                .url(requestURL)
                .put(requestBody)
                .addHeader("Accept", "application/json")
                .addHeader("Content-Type", "application/json")
                .build();

        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getActivity(), "Upload failure " + e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                            Toast.makeText(getActivity(), "Message: "+response , Toast.LENGTH_SHORT).show();

                    }
                });
            }
        });
    }

3. Now just call the above method as follows:

            try {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            uploadImageThroughMultipartPostRequest(fileToUpload);
                        }
                    }).start();
                } catch (Exception ex) {
                    ex.getMessage();
                }

That's all.
Share and comment if any issues.


No comments:

Post a Comment