Uploading file to server using Okhttp Android
In this post, i will show you how to upload a file to the server using the okhttp library. OkHTTP is an open source project designed to be an efficient HTTP client. It supports the SPDY protocol. SPDY is the basis for HTTP 2.0 and allows multiple HTTP requests to be multiplexed over one socket connection.
Step 1. Create a new project in the android studio and add following permission in android manifest.xml for the Internet, Storage, Camera, Network State.
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.CAMERA" />
Step 2. Add Okhttp dependency to build.gradle and click on sync.
compile 'com.squareup.okhttp3:okhttp:3.4.1'
Step 3. Check for Intenet, Storage, Camera permission is granted or not
//add this line in oncreate method
//create these methodint PERMISSION_ALL = 1; String[] PERMISSIONS = {android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.CAMERA}; if (!hasPermissions(this, PERMISSIONS)) { ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);}
Step 4. Now open activitymain.xml file and add following code to this filepublic static boolean hasPermissions(Context context, String... permissions) { if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) { for (String permission : permissions) { if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) { return false; } } } return true; } @Overridepublic void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { Log.v("heree", "Permission: " + permissions[0] + "was " + grantResults[0]); //resume tasks needing this permission } else { ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.CAMERA, android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE }, 1); } }
Step 5. Now open MainActivity.java and declare Image view, Button, and other fields. and set click on the button and open file chooser to select the file from storage.<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:gravity="center" android:orientation="vertical" tools:context="com.okhttpfileupload.MainActivity"> <ImageView android:id="@+id/tvFileName" android:layout_width="match_parent" android:layout_height="50dp" android:layout_gravity="center" android:padding="5dp" android:src="@drawable/camera" /> <TextView android:id="@+id/tvFile" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="5dp" android:gravity="center" android:text="" android:textColor="#cac7c7" android:textSize="12sp" /> <Button android:id="@+id/submit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_margin="10dp" android:background="@color/colorPrimary" android:gravity="center" android:text="post" android:textColor="#fff" /> </LinearLayout>
having = "0"; tvFile = (TextView) findViewById(R.id.tvFile); submit = (Button) findViewById(R.id.submit); tvFileName = (ImageView) findViewById(R.id.tvFileName); tvFileName.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final CharSequence[] items = {"Take Photo", "Choose from Library", "Cancel"}; AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle("Add Photo!"); builder.setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int item) { if (items[item].equals("Take Photo")) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent, 1); } else if (items[item].equals("Choose from Library")) { showFileChooser(); } else if (items[item].equals("Cancel")) { dialog.dismiss(); } } }); builder.show(); } }); submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MultipartBody.Builder formBodyBuilder = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("attachment", filename, RequestBody.create(MediaType.parse("text/csv/pdf/image"), f)); MultipartBody requestBody = formBodyBuilder.build(); final Request request = new Request.Builder() .url("https://demo.trinitytuts.com/api/upload") .post(requestBody) .build(); OkHttpClient client = new OkHttpClient(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, final Response response) throws IOException { if (!response.isSuccessful()) { throw new IOException("Unexpected code " + response); } else { // do something wih the result Log.e("TAG", "---------------" + response.body().string().toString()); String res = response.body().string().toString(); try { JSONObject object = new JSONObject(res); if (object.getString("status").equals("1")) { Toast.makeText(MainActivity.this, "Uploaded Successfully", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } } }); } });
private void showFileChooser() { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("*/*"); intent.addCategory(Intent.CATEGORY_OPENABLE); try { startActivityForResult( Intent.createChooser(intent, "Select a File to Upload"), FILE_SELECT_CODE); } catch (android.content.ActivityNotFoundException ex) { // Potentially direct the user to the Market with a Dialog Toast.makeText(this, "Please install a File Manager.", Toast.LENGTH_SHORT).show(); } } @Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { if (requestCode == FILE_SELECT_CODE) { if (data == null) { //no data present return; } selectedFileUri = data.getData(); selectedFilePath = FilePath.getPath(this, selectedFileUri); Log.i(TAG, "Selected File Path:" + selectedFilePath); if (selectedFilePath != null && !selectedFilePath.equals("")) { //tvFileNamestring=selectedFilePath; f = new File(getPath(selectedFileUri)); filename = selectedFilePath.substring(selectedFilePath.lastIndexOf("/") + 1); tvFile.setText(filename); having = "1"; } else { having = "0"; Toast.makeText(this, "Cannot upload file to server", Toast.LENGTH_SHORT).show(); } } else { Bitmap photo = (Bitmap) data.getExtras().get("data"); Uri tempUri = getImageUri(getApplicationContext(), photo); f = new File(getRealPathFromURI(tempUri)); filename = getRealPathFromURI(tempUri).substring(getRealPathFromURI(tempUri).lastIndexOf("/") + 1); tvFile.setText(filename); having = "1"; } } } public String getRealPathFromURI(Uri uri) { Cursor cursor = getContentResolver().query(uri, null, null, null, null); cursor.moveToFirst(); int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); return cursor.getString(idx);
}
public String getPath(Uri uri) { if (uri == null) { return null; } String result = null; String[] projection = {MediaStore.Images.Media.DATA}; Cursor cursor = getContentResolver().query(uri, projection, null, null, null); // deprecated: // Cursor cursor = managedQuery(uri, projection, null, null, null); if (cursor != null) { int columnIndex = 0; try { columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); result = cursor.getString(columnIndex); } catch (IllegalArgumentException e) { Log.e("While getting path for file", e.toString()); } finally { try { if (!cursor.isClosed()) { cursor.close(); } cursor = null; } catch (Exception e) { Log.e("While closing cursor", e.toString()); } } } return result; } public Uri getImageUri(Context inContext, Bitmap inImage) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes); String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Exozen", null); return Uri.parse(path);
}Step 6. Now Create new java class with name FilePath.java and add following code to this class
package com.okhttpfileupload; import android.content.ContentUris; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.provider.DocumentsContract; import android.provider.MediaStore; /** * Created by mogli on 4/20/2017. */ public class FilePath { public static String getPath(final Context context, final Uri uri) { // check here to KITKAT or new version final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; // DocumentProvider if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) { // ExternalStorageProvider if (isExternalStorageDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; if ("primary".equalsIgnoreCase(type)) { return Environment.getExternalStorageDirectory() + "/" + split[1]; } } // DownloadsProvider else if (isDownloadsDocument(uri)) { final String id = DocumentsContract.getDocumentId(uri); final Uri contentUri = ContentUris.withAppendedId( Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); return getDataColumn(context, contentUri, null, null); } // MediaProvider else if (isMediaDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; Uri contentUri = null; if ("image".equals(type)) { contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; } else if ("video".equals(type)) { contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; } else if ("audio".equals(type)) { contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } final String selection = "_id=?"; final String[] selectionArgs = new String[] { split[1] }; return getDataColumn(context, contentUri, selection, selectionArgs); } } // MediaStore (and general) else if ("content".equalsIgnoreCase(uri.getScheme())) { // Return the remote address if (isGooglePhotosUri(uri)) return uri.getLastPathSegment(); return getDataColumn(context, uri, null, null); } // File else if ("file".equalsIgnoreCase(uri.getScheme())) { return uri.getPath(); } return null; } /** * Get the value of the data column for this Uri. This is useful for * MediaStore Uris, and other file-based ContentProviders. * * @param context * The context. * @param uri * The Uri to query. * @param selection * (Optional) Filter used in the query. * @param selectionArgs * (Optional) Selection arguments used in the query. * @return The value of the _data column, which is typically a file path. */ public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { Cursor cursor = null; final String column = "_data"; final String[] projection = { column }; try { cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); if (cursor != null && cursor.moveToFirst()) { final int index = cursor.getColumnIndexOrThrow(column); return cursor.getString(index); } } finally { if (cursor != null) cursor.close(); } return null; } /** * @param uri * The Uri to check. * @return Whether the Uri authority is ExternalStorageProvider. */ public static boolean isExternalStorageDocument(Uri uri) { return "com.android.externalstorage.documents".equals(uri .getAuthority()); } /** * @param uri * The Uri to check. * @return Whether the Uri authority is DownloadsProvider. */ public static boolean isDownloadsDocument(Uri uri) { return "com.android.providers.downloads.documents".equals(uri .getAuthority()); } /** * @param uri * The Uri to check. * @return Whether the Uri authority is MediaProvider. */ public static boolean isMediaDocument(Uri uri) { return "com.android.providers.media.documents".equals(uri .getAuthority()); } /** * @param uri * The Uri to check. * @return Whether the Uri authority is Google Photos. */ public static boolean isGooglePhotosUri(Uri uri) { return "com.google.android.apps.photos.content".equals(uri .getAuthority()); }
}Step 7. Complete Code for MainActivity.java
package com.okhttpfileupload; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.MediaStore; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; public class MainActivity extends AppCompatActivity { private TextView tvFile; private Button submit; private ImageView tvFileName; private static final int FILE_SELECT_CODE = 0; private Uri selectedFileUri; private File f; private String TAG = "MAinActivity"; private String selectedFilePath; private String filename; private String having; private String response; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); int PERMISSION_ALL = 1; String[] PERMISSIONS = {android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.CAMERA}; if (!hasPermissions(this, PERMISSIONS)) { ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL); } having = "0"; tvFile = (TextView) findViewById(R.id.tvFile); submit = (Button) findViewById(R.id.submit); tvFileName = (ImageView) findViewById(R.id.tvFileName); tvFileName.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final CharSequence[] items = {"Take Photo", "Choose from Library", "Cancel"}; AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle("Add Photo!"); builder.setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int item) { if (items[item].equals("Take Photo")) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent, 1); } else if (items[item].equals("Choose from Library")) { showFileChooser(); } else if (items[item].equals("Cancel")) { dialog.dismiss(); } } }); builder.show(); } }); submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MultipartBody.Builder formBodyBuilder = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("attachment", filename, RequestBody.create(MediaType.parse("text/csv/pdf/image"), f)); MultipartBody requestBody = formBodyBuilder.build(); final Request request = new Request.Builder() .url("https://demo.trinitytuts.com/api/upload") .post(requestBody) .build(); OkHttpClient client = new OkHttpClient(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, final Response response) throws IOException { if (!response.isSuccessful()) { throw new IOException("Unexpected code " + response); } else { // do something wih the result Log.e("TAG", "---------------" + response.body().string().toString()); String res = response.body().string().toString(); try { JSONObject object = new JSONObject(res); if (object.getString("status").equals("1")) { Toast.makeText(MainActivity.this, "Uploaded Successfully", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } } }); } }); } private void showFileChooser() { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("*/*"); intent.addCategory(Intent.CATEGORY_OPENABLE); try { startActivityForResult( Intent.createChooser(intent, "Select a File to Upload"), FILE_SELECT_CODE); } catch (android.content.ActivityNotFoundException ex) { // Potentially direct the user to the Market with a Dialog Toast.makeText(this, "Please install a File Manager.", Toast.LENGTH_SHORT).show(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { if (requestCode == FILE_SELECT_CODE) { if (data == null) { //no data present return; } selectedFileUri = data.getData(); selectedFilePath = FilePath.getPath(this, selectedFileUri); Log.i(TAG, "Selected File Path:" + selectedFilePath); if (selectedFilePath != null && !selectedFilePath.equals("")) { //tvFileNamestring=selectedFilePath; f = new File(getPath(selectedFileUri)); filename = selectedFilePath.substring(selectedFilePath.lastIndexOf("/") + 1); tvFile.setText(filename); having = "1"; } else { having = "0"; Toast.makeText(this, "Cannot upload file to server", Toast.LENGTH_SHORT).show(); } } else { Bitmap photo = (Bitmap) data.getExtras().get("data"); Uri tempUri = getImageUri(getApplicationContext(), photo); f = new File(getRealPathFromURI(tempUri)); filename = getRealPathFromURI(tempUri).substring(getRealPathFromURI(tempUri).lastIndexOf("/") + 1); tvFile.setText(filename); having = "1"; } } } public String getRealPathFromURI(Uri uri) { Cursor cursor = getContentResolver().query(uri, null, null, null, null); cursor.moveToFirst(); int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); return cursor.getString(idx); } public static boolean hasPermissions(Context context, String... permissions) { if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) { for (String permission : permissions) { if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) { return false; } } } return true; } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { Log.v("heree", "Permission: " + permissions[0] + "was " + grantResults[0]); //resume tasks needing this permission } else { ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.CAMERA, android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE }, 1); } } public String getPath(Uri uri) { if (uri == null) { return null; } String result = null; String[] projection = {MediaStore.Images.Media.DATA}; Cursor cursor = getContentResolver().query(uri, projection, null, null, null); // deprecated: // Cursor cursor = managedQuery(uri, projection, null, null, null); if (cursor != null) { int columnIndex = 0; try { columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); result = cursor.getString(columnIndex); } catch (IllegalArgumentException e) { Log.e("While getting path for file", e.toString()); } finally { try { if (!cursor.isClosed()) { cursor.close(); } cursor = null; } catch (Exception e) { Log.e("While closing cursor", e.toString()); } } } return result; } public Uri getImageUri(Context inContext, Bitmap inImage) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes); String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Exozen", null); return Uri.parse(path); }
}Thank You :)
To Download code Click here!!
Comments
Post a Comment