PHP File
<?php
$con=new MySQLi("localhost","","","");
if($_SERVER['REQUEST_METHOD']=='POST'){
$image = $_POST['img'];
$name = $_POST['name'];
$sql ="SELECT * from img";
$res = mysqli_query($con,$sql);
$id = 0;
while($row = mysqli_fetch_array($res)){
$id = $row['id'];
}
$path = "upload/$id.pdf";
$actualpath = "URL/$path";
$sql = "INSERT INTO img (img,name) VALUES ('$actualpath','$name')";
if(mysqli_query($con,$sql)){
file_put_contents($path,base64_decode($image));
echo "Successfully Uploaded";
}
mysqli_close($con);
}else{
echo "Error";
}
public interface ApiConfig {
@Multipart
@POST("uploadpdf.php")
Call<ServerResponse> uploadFile(@Part MultipartBody.Part file,
@Part("name") RequestBody name);
}
public class AppConfig {
public static String BASE_URL="https://xyz.com/";
public static Retrofit getRetrofit(){
return new Retrofit.Builder()
.baseUrl(AppConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}public class MainActivity extends AppCompatActivity {
Button pic_img, pic_vdo, upload;
ProgressDialog progressDialog;
ImageView imgView;
String mediapath;
String mediaColumn[] = {MediaStore.Video.Media._ID};
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
setContentView(R.layout.activity_main);
progressDialog = new ProgressDialog(MainActivity.this);
pic_img = (Button) findViewById(R.id.pic_img);
imgView = (ImageView) findViewById(R.id.imgView);
pic_vdo = (Button) findViewById(R.id.pic_vdo);
upload = (Button) findViewById(R.id.upload);
upload.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
uploadFile();
}
});
pic_img.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
/* Intent galleryIntent=new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(galleryIntent,0);*/ Intent intent = new Intent();
intent.setType("application/pdf");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select PDF"), 0);
}
});
pic_vdo.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, 1);
}
});
}
private void uploadFile() { progressDialog.show(); Map<String, RequestBody> map = new HashMap<>(); File file = new File(mediapath);
RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file); MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), requestBody); RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), file.getName());
ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class); Call<ServerResponse> call = getResponse.uploadFile(fileToUpload, filename);
call.enqueue(new Callback<ServerResponse>() { @Override public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) { ServerResponse server = response.body();
if (server.getSuccess()) { Toast.makeText(MainActivity.this, "Hello" + server.getMessage(), Toast.LENGTH_SHORT).show(); } else { Log.d("Respon", server.toString()); }
progressDialog.dismiss();
}
@Override public void onFailure(Call<ServerResponse> call, Throwable t) { progressDialog.dismiss();
Toast.makeText(MainActivity.this, "" + t.getMessage(), Toast.LENGTH_SHORT).show(); } });
@RequiresApi(api = Build.VERSION_CODES.KITKAT) }
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 0 && resultCode == RESULT_OK && null != data) { Uri selectedImage = data.getData(); mediapath = getPath(this,selectedImage); Log.e("PATH", mediapath); /*String[] filePathColumn={MediaStore.Images.Media.DATA}; Cursor cursor=getContentResolver().query(selectedImage,filePathColumn,null,null,null); assert cursor!=null; cursor.moveToFirst(); int clumnIndex=cursor.getColumnIndex(filePathColumn[0]); mediapath=cursor.getString(clumnIndex); imgView.setImageBitmap(BitmapFactory.decodeFile(mediapath)); cursor.close();*/ } else if (requestCode == 1 && resultCode == RESULT_OK && null != data) { Uri selectedVideo = data.getData(); String[] filePathColumn = {MediaStore.Video.Media.DATA}; Cursor cursor = getContentResolver().query(selectedVideo, filePathColumn, null, null, null); assert cursor != null; cursor.moveToFirst(); int clumnIndex = cursor.getColumnIndex(filePathColumn[0]); mediapath = cursor.getString(clumnIndex); imgView.setImageBitmap(getThumbnail(MainActivity.this, selectedVideo)); cursor.close(); } else { Toast.makeText(this, "Havent picked", Toast.LENGTH_SHORT).show(); }
private Bitmap getThumbnail(Activity mainActivity, Uri selectedVideo) { }
long fileId = getFileId(mainActivity, selectedVideo); return MediaStore.Video.Thumbnails.getThumbnail(mainActivity.getContentResolver(), fileId, MediaStore.Video.Thumbnails.MINI_KIND, null); } private long getFileId(Activity mainActivity, Uri selectedVideo) { Cursor cursor = mainActivity.managedQuery(selectedVideo, mediaColumn, null, null, null); if (cursor.moveToFirst()) { int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID); return cursor.getInt(columnIndex); }
return 0; }
@RequiresApi(api = Build.VERSION_CODES.KITKAT) 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; } 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()); }
}public class ServerResponse {
@SerializedName("success")
boolean success;
@SerializedName("message")
String message;
String getMessage() {
return message;
}
boolean getSuccess() {
return success;
}
}
activity_main.xml<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.dataupload.MainActivity">
<ImageView
android:id="@+id/imgView"
android:layout_width="match_parent"
android:layout_height="300dp"
android:scaleType="centerCrop" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<Button
android:id="@+id/pic_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Pick Image" />
</LinearLayout>
<Button
android:id="@+id/upload"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Upload" />
</LinearLayout>
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />Database Design
public interface ApiConfig {
@Multipart
@POST("uploadpdf.php")
Call<ServerResponse> uploadFile(@Part MultipartBody.Part file,
@Part("name") RequestBody name);
}
public class AppConfig {
public static String BASE_URL="https://xyz.com/";
public static Retrofit getRetrofit(){
return new Retrofit.Builder()
.baseUrl(AppConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}public class MainActivity extends AppCompatActivity {
Button pic_img, pic_vdo, upload;
ProgressDialog progressDialog;
ImageView imgView;
String mediapath;
String mediaColumn[] = {MediaStore.Video.Media._ID};
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
setContentView(R.layout.activity_main);
progressDialog = new ProgressDialog(MainActivity.this);
pic_img = (Button) findViewById(R.id.pic_img);
imgView = (ImageView) findViewById(R.id.imgView);
pic_vdo = (Button) findViewById(R.id.pic_vdo);
upload = (Button) findViewById(R.id.upload);
upload.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
uploadFile();
}
});
pic_img.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
/* Intent galleryIntent=new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(galleryIntent,0);*/ Intent intent = new Intent();
intent.setType("application/pdf");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select PDF"), 0);
}
});
pic_vdo.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, 1);
}
});
}
private void uploadFile() { progressDialog.show(); Map<String, RequestBody> map = new HashMap<>(); File file = new File(mediapath);
RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file); MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), requestBody); RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), file.getName());
ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class); Call<ServerResponse> call = getResponse.uploadFile(fileToUpload, filename);
call.enqueue(new Callback<ServerResponse>() { @Override public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) { ServerResponse server = response.body();
if (server.getSuccess()) { Toast.makeText(MainActivity.this, "Hello" + server.getMessage(), Toast.LENGTH_SHORT).show(); } else { Log.d("Respon", server.toString()); }
progressDialog.dismiss();
}
@Override public void onFailure(Call<ServerResponse> call, Throwable t) { progressDialog.dismiss();
Toast.makeText(MainActivity.this, "" + t.getMessage(), Toast.LENGTH_SHORT).show(); } });
@RequiresApi(api = Build.VERSION_CODES.KITKAT) }
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 0 && resultCode == RESULT_OK && null != data) { Uri selectedImage = data.getData(); mediapath = getPath(this,selectedImage); Log.e("PATH", mediapath); /*String[] filePathColumn={MediaStore.Images.Media.DATA}; Cursor cursor=getContentResolver().query(selectedImage,filePathColumn,null,null,null); assert cursor!=null; cursor.moveToFirst(); int clumnIndex=cursor.getColumnIndex(filePathColumn[0]); mediapath=cursor.getString(clumnIndex); imgView.setImageBitmap(BitmapFactory.decodeFile(mediapath)); cursor.close();*/ } else if (requestCode == 1 && resultCode == RESULT_OK && null != data) { Uri selectedVideo = data.getData(); String[] filePathColumn = {MediaStore.Video.Media.DATA}; Cursor cursor = getContentResolver().query(selectedVideo, filePathColumn, null, null, null); assert cursor != null; cursor.moveToFirst(); int clumnIndex = cursor.getColumnIndex(filePathColumn[0]); mediapath = cursor.getString(clumnIndex); imgView.setImageBitmap(getThumbnail(MainActivity.this, selectedVideo)); cursor.close(); } else { Toast.makeText(this, "Havent picked", Toast.LENGTH_SHORT).show(); }
private Bitmap getThumbnail(Activity mainActivity, Uri selectedVideo) { }
long fileId = getFileId(mainActivity, selectedVideo); return MediaStore.Video.Thumbnails.getThumbnail(mainActivity.getContentResolver(), fileId, MediaStore.Video.Thumbnails.MINI_KIND, null); } private long getFileId(Activity mainActivity, Uri selectedVideo) { Cursor cursor = mainActivity.managedQuery(selectedVideo, mediaColumn, null, null, null); if (cursor.moveToFirst()) { int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID); return cursor.getInt(columnIndex); }
return 0; }
@RequiresApi(api = Build.VERSION_CODES.KITKAT) 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; } 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()); }
}public class ServerResponse {
@SerializedName("success")
boolean success;
@SerializedName("message")
String message;
String getMessage() {
return message;
}
boolean getSuccess() {
return success;
}
}
activity_main.xml<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.dataupload.MainActivity">
<ImageView
android:id="@+id/imgView"
android:layout_width="match_parent"
android:layout_height="300dp"
android:scaleType="centerCrop" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<Button
android:id="@+id/pic_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Pick Image" />
</LinearLayout>
<Button
android:id="@+id/upload"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Upload" />
</LinearLayout>
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />Database Design
This comment has been removed by the author.
ReplyDeleteThis comment has been removed by the author.
ReplyDelete