Sahana P
Sahana P

Reputation: 73

How to post an image to server in android

How do I upload an image to the Server? Both MultiPArtEntity and MultiPartEntityBuilder classes are deprecated in API level 23. Can we do this using HTTPUrlConnection or volley?

Upvotes: 2

Views: 1221

Answers (2)

Hardy
Hardy

Reputation: 2606

Hello totally above answer is correct and accepted but here is the another solution the easiest way ever for posting image to the server:-

Using rest api from andoid spring framework in your android project just create new custom interface as below :-

@Rest(rootUrl ="BASE_URL", converters = {ByteArrayHttpMessageConverter.class,
    FormHttpMessageConverter.class, StringHttpMessageConverter.class})
public interface CustomRest extends RestClientErrorHandling {

@Post("YourPostfixforUrl")
String _postImage(MultiValueMap<String, Object> multiValueMap);

}

Create your own RestErrorHandler using below code:-

@EBean
public class CustomRestErrorHandler implements RestErrorHandler
{
    @Override
    public void onRestClientExceptionThrown(NestedRuntimeException e)
    {
        Log.e("NestedRuntimeException ", "NestedRuntimeException :- " + e.toString());
    }
}

On Your activity call bellow code :-

 @AfterInject
public void afterInject() {
    MultiValueMap<String, Object> ObjectMultiValueMap = new LinkedMultiValueMap<>();
    ObjectMultiValueMap.add("yourImageKey", new FileSystemResource(new File("yourFilePath")));
    doInBackground(myrest, ObjectMultiValueMap);
}

@Background
public void doInBackground(Myrest myrest, MultiValueMap<String, Object> multiValueMap) {
    myrest.setRestErrorHandler(myErrorHandler);

}

Your Gradle will look like below:-

def AAVersion = '3.3.2'    
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
apt "org.androidannotations:androidannotations:$AAVersion"
compile "org.androidannotations:androidannotations-api:$AAVersion"
compile 'org.springframework.android:spring-android-core:1.0.1.RELEASE'
compile 'org.springframework.android:spring-android-rest-template:1.0.1.RELEASE'}

NOTE:- Your activity Must be @Eactivity

--> I Guess androidannotation+rest is the best time saver and sincerely optimizing the code snippets! Thanks

Upvotes: 1

BNK
BNK

Reputation: 24114

I suggest that you use OkHttp. More details about it you can find at the following:

OkHttp - An HTTP & SPDY client for Android and Java applications

Please refer to my basic sample code that uploads a PNG file from drawable folder to remote web service. Hope this helps!

...
    mTextView = (TextView) findViewById(R.id.textView);
    mHandler = new Handler(Looper.getMainLooper());
...
    Drawable drawable = getResources().getDrawable(R.drawable.ic_launcher);
    if (drawable != null) {
        Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 0, stream);
        final byte[] bitmapdata = stream.toByteArray();

        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new MultipartBuilder()
                .type(MultipartBuilder.FORM)
                .addPart(
                        Headers.of("Content-Disposition", "form-data; name=\"file\"; filename=\"ic_launcher.png\""),
                        RequestBody.create(MEDIA_TYPE_PNG, bitmapdata))
                .build();
        final Request request = new Request.Builder()
                .url("http://myserver/api/files")
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(final Request request, final IOException e) {
                Log.e(LOG_TAG, e.toString());
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mContext, e.toString(), Toast.LENGTH_SHORT).show();
                        mTextView.setText(e.toString());
                    }
                });
            }

            @Override
            public void onResponse(Response response) throws IOException {
                final String message = response.toString();
                Log.i(LOG_TAG, message);
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
                        mTextView.setText(message);
                    }
                });
            }
        });
    }

Upvotes: 1

Related Questions