XMLRPC Wordpress Image Upload - Uploads Empty Image? - java

I am trying to upload an image file to a Wordpress Site using XMLRPC.
I'm using org.apache.xmlrpc:xmlrpc-client to make the connection from Android, and I can successfully hit the website, and fire the upload, but the image file is empty on the site. I've sent through a base64 encoded string as the WP API states but I just can't get it to work?
Anyone know why?
This is my code:
public static void updatePhoto(final String status, final Context context, final String uri) {
websiteUrl = (String) loadPreference("wordpressUrl", context,String.class);
username = (String) loadPreference("wordpressUsername", context,String.class);
password = (String) loadPreference("wordpressPassword", context,String.class);
AsyncTask.execute(new Runnable() {
#Override
public void run() {
try {
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
config.setServerURL(new URL(websiteUrl+"/xmlrpc.php"));
XmlRpcClient rpcClient = new XmlRpcClient();
rpcClient.setConfig(config);
Uri realUri = getImageContentUri(context,Uri.parse(uri).getPath());
final InputStream imageStream = context.getContentResolver().openInputStream(realUri);
Bitmap originalBitmap = BitmapFactory.decodeStream(imageStream);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
originalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] outputByteArray = baos.toByteArray();
String base64EncodedString = Base64.encodeToString(outputByteArray, Base64.DEFAULT);
Map content = new Hashtable();
content.put("name", status+".jpg");
content.put("type", "image/jpeg");
content.put("bits", base64EncodedString);
content.put("overwrite", false);
// Make the XMLRPC call.
Object result = rpcClient.execute("wp.uploadFile", new Object[]{
0,
username,
password,
content
});
// Print result - this is the new post's ID.
System.out.println(result);
} catch (final XmlRpcException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
}
});
} catch (final Exception e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
});
}
public static Uri getImageContentUri(Context context, String absPath) {
Log.v(TAG, "getImageContentUri: " + absPath);
Cursor cursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
, new String[] { MediaStore.Images.Media._ID }
, MediaStore.Images.Media.DATA + "=? "
, new String[] { absPath }, null);
if (cursor != null && cursor.moveToFirst()) {
int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
return Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI , Integer.toString(id));
} else if (!absPath.isEmpty()) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, absPath);
return context.getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} else {
return null;
}
}
private static String encodeImage(Bitmap bm)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,100,baos);
byte[] b = baos.toByteArray();
String encImage = Base64.encodeToString(b, Base64.NO_WRAP);
return encImage;
}

Related

How to get PDF File Path In Android 11 and 12

I tried much code for getting pdf path in android 11 or 12 but only working in android 10 or below devices.
Can you please help me? I share my code of lines
Intent calling like this
Intent intent = new Intent();
intent.setType("application/pdf");
statusAdapter = "pdf";
pos = position;
intent.setAction(Intent.ACTION_GET_CONTENT);
someActivityResultLauncher.launch(Intent.createChooser(intent, "Select PDF"));
someActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == Activity.RESULT_OK) {
// There are no request codes
Intent data = result.getData();
if (data == null) {
//error
return;
}
try {
final Uri pdfUri= data.getData();
File pdfFile = new File(getPath(pdfUri));
long length = pdfFile.length();
length = length / 1024;
Toast.makeText(CreateSubEventActivity.this, "File Path : " + pdfFile.getPath() + ", File size : " + length + " KB", Toast.LENGTH_SHORT).show();
// uploadFile(imageFile);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(CreateSubEventActivity.this, "Something went wrong", Toast.LENGTH_LONG).show();
}
}
});
getPath calling like this
public String getPath(Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if (cursor == null) return null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String s = cursor.getString(column_index);
cursor.close();
return s;
}
If you want to access a File or want a file path from a Uri that was returned from MediaStore, I have got a library that handles all the exceptions you might get. This includes all files on the disk, internal and removable disk. When selecting a File from Dropbox, for example, the File will be copied to your applications directory where you have full access, the copied file path will then be returned.
Let me share my experience to fix this stuff after so reading all.
Get input stream from URI
final Uri pdfUri= data.getData();
getContentResolver().openInputStream(pdfUri)
then do your stuff with InputStream, like I have uploaded pdf using okHttp
try {
RequestBody pdffile = new RequestBody() {
#Override public MediaType contentType() { return MediaType.parse("application/pdf"); }
#Override public void writeTo(BufferedSink sink) throws IOException {
Source source = null;
try {
source = Okio.source(inputStream);
sink.writeAll(source);
} finally {
Util.closeQuietly(source);
}
}
#Override
public long contentLength() {
try {
return inputStream.available();
} catch (IOException e) {
return 0;
}
}
};
RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("file", "fname.pdf", pdffile)
//.addFormDataPart("Documents", value) // uncomment if you want to send Json along with file
.build();
Request request = new Request.Builder()
.url(serverURL)
.post(requestBody)
.build();
OkHttpClient client = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS).writeTimeout(180, TimeUnit.SECONDS).readTimeout(180, TimeUnit.SECONDS)
.addInterceptor(chain -> {
Request original = chain.request();
Request.Builder builder = original.newBuilder().method(original.method(), original.body());
builder.header("key", key);
return chain.proceed(builder.build());
})
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(final Call call, final IOException e) {
// Handle the error
setIsLoading(false);
getNavigator().uploadIssue("Facing some issue to upload this file.");
}
#Override
public void onResponse(final Call call, final Response response) throws IOException {
setIsLoading(false);
if (!response.isSuccessful()) {
getNavigator().uploadIssue("Facing some issue to upload this file.");
}else {
// Upload successful
getNavigator().uploadedSucessfully();
}
}
});
return true;
} catch (Exception ex) {
// Handle the error
ex.printStackTrace();
}
This one helps in my case on Android 11 hope anyone gets this helpful
private String copyFile(Uri uri, String newDirName) {
Uri returnUri = uri;
Cursor returnCursor = this.getContentResolver().query(returnUri, new String[]{
OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE
}, null, null, null);
/*
* Get the column indexes of the data in the Cursor,
* * move to the first row in the Cursor, get the data,
* * and display it.
* */
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
returnCursor.moveToFirst();
String name = (returnCursor.getString(nameIndex));
String size = (Long.toString(returnCursor.getLong(sizeIndex)));
File output;
if (!newDirName.equals("")) {
File dir = new File(this.getFilesDir() + "/" + newDirName);
if (!dir.exists()) {
dir.mkdir();
}
output = new File(this.getFilesDir() + "/" + newDirName + "/" + name);
} else {
output = new File(this.getFilesDir() + "/" + name);
}
try {
InputStream inputStream = this.getContentResolver().openInputStream(uri);
FileOutputStream outputStream = new FileOutputStream(output);
int read = 0;
int bufferSize = 1024;
final byte[] buffers = new byte[bufferSize];
while ((read = inputStream.read(buffers)) != -1) {
outputStream.write(buffers, 0, read);
}
inputStream.close();
outputStream.close();
} catch (Exception e) {
Log.e("Exception", e.getMessage());
}
return output.getPath();
}
String newPath = copyFileToInternalStorage(uri, getResources().getString(R.string.app_name));

Firebase StorageReference.getFile is not working - FirebaseStorage Android

I am trying to download a file in my AsyncTask from Firebase Storage as below:
static class DownloadFileFromFireBase extends AsyncTask<String, Void, Boolean> {
File file;
String fileName;
boolean downloadStatus = false;
public DownloadFileFromFireBase(Context context,String fileName, File file){
this.fileName = fileName;
this.file = file;
}
protected Boolean doInBackground(String... urls) {
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReference();
StorageReference dataRef = storageRef.child(fileName);
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
dataRef.getFile(file).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Log.d(TAG,"File Downloaded");
downloadStatus = true;
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.d(TAG,"File Download Failed");
downloadStatus = false;
}
});
return downloadStatus;
}
protected void onPostExecute(InputStream contentsInputStream) {
//TODO:
}
}
My program neither goes into addOnSuccessListener nor in addOnFailureListener listners (no logs printed in Logcat)
I have temporarily set my Firebase rules as below:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read: if request.auth == null;
}
}
}
I am calling my AsyncTask as below:
boolean status = new DownloadFileFromFireBase(getContext(), contentsJsonFile).execute("").get();
My files stored on the Firebase storage are accessible from web browser (where I am not logged in/an incognito mode).
My Emulator and Device are using latest Google Services.
Even Firebase Storage API implemented in my project is the latest one (19.1.1).
I am not sure what is going wrong in here.
Any help would be appreciated! Thanks.
FirebaseStorage Android SDK getFile(file) seems no longer work properly in Android Q (SDK 29) which is a breaking changes. You may use getBytes(file_size) like this.
//Member variable but depending on your scope
private ByteArrayInputStream inputStream;
private Uri downloadedFileUri;
private OutputStream stream;
//Creating a reference to the link
StorageReference httpsReference = FirebaseStorage.getInstance().getReferenceFromUrl(downloadURL);
Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String type = "";
String mime = "";
String folderName = "";
if (downloadURL.contains("jpg") || downloadURL.contains("jpeg")
|| downloadURL.contains("png") || downloadURL.contains("webp")
|| downloadURL.contains("tiff") || downloadURL.contains("tif")) {
type = ".jpg";
mime = "image/*";
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
folderName = Environment.DIRECTORY_PICTURES;
}
if (downloadURL.contains(".gif")){
type = ".gif";
mime = "image/*";
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
folderName = Environment.DIRECTORY_PICTURES;
}
if (downloadURL.contains(".mp4") || downloadURL.contains(".avi")){
type = ".mp4";
mime = "video/*";
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
folderName = Environment.DIRECTORY_MOVIES;
}
if (downloadURL.contains(".mp3")){
type = ".mp3";
mime = "audio/*";
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
folderName = Environment.DIRECTORY_MUSIC;
}
final String relativeLocation = folderName + "/" + getString(R.string.app_name);
final ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, UUID.randomUUID().toString() + type);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, mime); //Cannot be */*
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, relativeLocation);
ContentResolver resolver = getContentResolver();
Uri uriResolve = resolver.insert(contentUri, contentValues);
try {
if (uriResolve == null || uriResolve.getPath() == null) {
throw new IOException("Failed to create new MediaStore record.");
}
stream = resolver.openOutputStream(uriResolve);
//This is 1GB change this depending on you requirements
httpsReference.getBytes(1024 * 1024 * 1024)
.addOnSuccessListener(bytes -> {
try {
int bytesRead;
inputStream = new ByteArrayInputStream(bytes);
while ((bytesRead = inputStream.read(bytes)) > 0) {
stream.write(bytes, 0, bytesRead);
}
inputStream.close();
stream.flush();
stream.close();
//FINISH
} catch (IOException e) {
closeSession(resolver, uriResolve, e);
e.printStackTrace();
Crashlytics.logException(e);
}
});
} catch (IOException e) {
closeSession(resolver, uriResolve, e);
e.printStackTrace();
Crashlytics.logException(e);
}
A better replacement if you want to monitor the download progress is by using getStream(), with this you can compute the downloaded bytes from total bytes to download.
httpsReference.getStream((state, inputStream) -> {
long totalBytes = state.getTotalByteCount();
long bytesDownloaded = 0;
byte[] buffer = new byte[1024];
int size;
while ((size = inputStream.read(buffer)) != -1) {
stream.write(buffer, 0, size);
bytesDownloaded += size;
showProgressNotification(bytesDownloaded, totalBytes, requestCode);
}
// Close the stream at the end of the Task
inputStream.close();
stream.flush();
stream.close();
}).addOnSuccessListener(taskSnapshot -> {
showDownloadFinishedNotification(downloadedFileUri, downloadURL, true, requestCode);
//Mark task as complete so the progress download notification whether success of fail will become removable
taskCompleted();
contentValues.put(MediaStore.Files.FileColumns.IS_PENDING, false);
resolver.update(uriResolve, contentValues, null, null);
}).addOnFailureListener(e -> {
Log.w(TAG, "download:FAILURE", e);
try {
stream.flush();
stream.close();
} catch (IOException ioException) {
ioException.printStackTrace();
FirebaseCrashlytics.getInstance().recordException(ioException);
}
FirebaseCrashlytics.getInstance().recordException(e);
//Send failure
showDownloadFinishedNotification(null, downloadURL, false, requestCode);
//Mark task as complete
taskCompleted();
});
Check the sample project to learn more: https://github.com/firebase/quickstart-android/tree/master/storage

How to upload video in android using volley

I am trying to upload a video on the server, I didn't anything on this, please suggest
I can upload the text, that's working,
RequestQueue requestQueue = Volley.newRequestQueue(mContext);
StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://54.146.132.94/webservices/target_response",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(mContext, "" + response, Toast.LENGTH_SHORT).show();
Log.i("error", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(mContext, "" + error.toString(), Toast.LENGTH_SHORT).show();
Log.i("error", error.toString());
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("I_trails", String.valueOf(itr));
params.put("E_trails", String.valueOf(et));
params.put("D_trails", String.valueOf(dt));
params.put("N_trails", String.valueOf(nt));
params.put("user_id", String.valueOf(get_id));
params.put("target_id", String.valueOf(get_target_id));
params.put("session_date", date);
params.put("data_mode", data_mode);
params.put("mode", mode);
params.put("link", link);
// params.put("video", selectedPath);
params.put("time", time_upload_real);
params.put("location_id", LocID);
params.put("No_of_trails", String.valueOf(notr));
/*params.put("comment", my_comment);*/
return params;
}
};
// Adding the StringRequest object into requestQueue.
requestQueue.add(stringRequest);
here the code to upload video, please let me know how to upload this video with the data, that I am uploading.
if (null != selectedPath && !selectedPath.isEmpty()){
Toast.makeText(mContext, "selected path: "+selectedPath, Toast.LENGTH_SHORT).show();
new Thread(new Runnable() {
#Override
public void run() {
//creating new thread to handle Http Operations
uploadFile(selectedPath);
}
}).start();
then,
public int uploadFile(final String selectedPath){
int serverResponseCode = 0;
HttpURLConnection connection;
DataOutputStream dataOutputStream;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead,bytesAvailable,bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File selectedFile = new File(selectedPath);
try {
FileInputStream fileInputStream = new FileInputStream(selectedFile);
URL url = new URL("http://54.146.132.94/webservices/target_response");
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);//Allow Inputs
connection.setDoOutput(true);//Allow Outputs
connection.setUseCaches(false);//Don't use a cached Copy
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("ENCTYPE", "multipart/form-data");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("video",selectedPath);
//creating new dataoutputstream
dataOutputStream = new DataOutputStream(connection.getOutputStream());
//writing bytes to data outputstream
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"video\";filename=\""
+ selectedPath + "\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
//returns no. of bytes present in fileInputStream
bytesAvailable = fileInputStream.available();
//selecting the buffer size as minimum of available bytes or 1 MB
bufferSize = Math.min(bytesAvailable,maxBufferSize);
//setting the buffer as byte array of size of bufferSize
buffer = new byte[bufferSize];
//reads bytes from FileInputStream(from 0th index of buffer to buffersize)
bytesRead = fileInputStream.read(buffer,0,bufferSize);
//loop repeats till bytesRead = -1, i.e., no bytes are left to read
while (bytesRead > 0){
//write the bytes read from inputstream
dataOutputStream.write(buffer,0,bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
bytesRead = fileInputStream.read(buffer,0,bufferSize);
}
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
//closing the input and output streams
fileInputStream.close();
dataOutputStream.flush();
dataOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// dialog.dismiss();
return serverResponseCode;
}
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_GALLERY);
and after selecting video
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
if (requestCode == PICK_FROM_GALLERY) {
Uri aa = data.getData();
mVideoURI = Uri.parse(String.valueOf(aa));
}
}
dont forget to use private Uri mVideoURI;
at top
inside your post volley method use :
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
/// photo field in link
if (mVideoURI != null) {
params.put("video", new DataPart("file_avatar.mp4", UploadHelper.getFileDataFromDrawable(getActivity(), mVideoURI)));
}
return params;
}
UPDATE
1- CREATE BroadcastHelper CLASS :
public class BroadcastHelper {
public static final String BROADCAST_EXTRA_METHOD_NAME = "INPUT_METHOD_CHANGED";
public static final String ACTION_NAME = "hassan.scott";
private static final String UPDATE_LOCATION_METHOD = "update";
public static void sendInform(Context context, String method) {
Intent intent = new Intent();
intent.setAction(ACTION_NAME);
intent.putExtra(BROADCAST_EXTRA_METHOD_NAME, method);
try {
context.sendBroadcast(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void sendInform(Context context, String method, Intent intent) {
intent.setAction(ACTION_NAME);
intent.putExtra(BROADCAST_EXTRA_METHOD_NAME, method);
try {
context.sendBroadcast(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
2- Send intent from your adapter
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent url = new Intent("url");
url ("url_adapter",item.get(position).getURL());
BroadcastHelper.sendInform(context,"url",url);
}
});
3- in your fragment this use :
Receiver receiver;
boolean isReciverRegistered = false;
#Override
public void onResume() {
super.onResume();
if (receiver == null) {
receiver = new Receiver();
IntentFilter filter = new IntentFilter(BroadcastHelper.ACTION_NAME);
getActivity().registerReceiver(receiver, filter);
isReciverRegistered = true;
}
}
#Override
public void onDestroy() {
if (isReciverRegistered) {
if (receiver != null)
getActivity().unregisterReceiver(receiver);
}
super.onDestroy();
}
private class Receiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
Log.v("r", "receive " + arg1.getStringExtra(BroadcastHelper.BROADCAST_EXTRA_METHOD_NAME));
String methodName = arg1.getStringExtra(BroadcastHelper.BROADCAST_EXTRA_METHOD_NAME);
if (methodName != null && methodName.length() > 0) {
Log.v("receive", methodName);
switch (methodName) {
case "url":
/* call post method here */
default:
break;
}
}
}
}
UploadHelper Class :
public class UploadHelper {
/**
* Turn drawable resource into byte array.
*
* #param context parent context
* #param id drawable resource id
* #return byte array
*/
public static byte[] getFileDataFromDrawable(Context context, int id) {
Drawable drawable = ContextCompat.getDrawable(context, id);
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}
/**
* Turn drawable into byte array.
*
* #return byte array
*/
public static byte[] getFileDataFromDrawable(Context context, Uri uri) {
// Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
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();
}
}
Volley wasn't really meant for video uploading. It is better suited to large in number - small in size uploads/downloads. I would recommend using a different method to upload your video.
Volley is not suitable for large download or streaming operations,
since Volley holds all responses in memory during parsing. For large
download operations, consider using an alternative like
DownloadManager.*
Taken from https://developer.android.com/training/volley/

I am having error to display the image file save in memory in android,

Here is the code:
public void Displayimg(View v) {
File path = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyCameraApp");
ipath[0] = String.valueOf(((TextView) v).getText());
String sifile = ipath[0].substring(45,52); // extracting the filename from the view eg: abc.jpg
File imgfile = new File(path,sifile); // it fails on this line with unfortunately, main application has stopped.
// if the sifile conatians a name of the file that exist, it give error and comes out
// if I give file name in sifile that does not exisit, if give file does on exisit and comes our with error.
// Basically I am having problem to open an image file that exisit and dispaly.
// File("/storage/sdcard0/Pictures/MyCameraApp/Zimg20151105_1535133.Jpg");
Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.mc_imgview);
if(imgfile.exists()){
Toast.makeText(getApplicationContext(),file.getAbsolutePath() + "File Exisit", Toast.LENGTH_SHORT).show();
myImage.setImageBitmap(myBitmap);
}
else
{
Toast.makeText(getApplicationContext(),file.getAbsolutePath() + " File Does not Exisit", Toast.LENGTH_SHORT).show();
}
}
Display image :
Try to Search Volley or Universal-Image-Loader or Glide.
Save Image:
public static String getSdPath(){
//todo test path
return Environment.getExternalStorageDirectory().getAbsolutePath();
// return "";
}
public static String getImageDir (String type,Activity activity){
if(type.equalsIgnoreCase("pure")){
return getSdPath()+ activity.getDir("pure", Context.MODE_PRIVATE).getAbsolutePath();
}else{
return getSdPath()+activity.getDir("deal", Context.MODE_PRIVATE).getAbsolutePath();
}
}
private static final String APPLICATION_NAME = "test";
private static final Uri IMAGE_URI = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
private static final String PATH = getImageDir("deal", mActivity);
public static Uri savePngImage(ContentResolver cr, Bitmap bitmap) {
long dateTaken = System.currentTimeMillis();
String name = String.valueOf(dateTaken) + ".png";
return savePngImage(cr, name, dateTaken, PATH, name, bitmap);
}
public static Uri savePngImage(ContentResolver cr, String name, long dateTaken, String directory,
String filename, Bitmap source) {
OutputStream outputStream = null;
String filePath = directory + File.separator + filename;
try {
File dir = new File(directory);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(directory, filename);
if (file.createNewFile()) {
outputStream = new FileOutputStream(file);
if (source != null) {
source.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
} else {
}
}
// FileUtils.updateFile(file);
} catch (FileNotFoundException ex) {
return null;
} catch (IOException ex) {
return null;
} catch (NullPointerException ex) {
return null;
}finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (Throwable t) {
}
}
}
ContentValues values = new ContentValues(7);
values.put(MediaStore.Images.Media.TITLE, name);
values.put(MediaStore.Images.Media.DISPLAY_NAME, filename);
values.put(MediaStore.Images.Media.DATE_TAKEN, dateTaken);
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.Images.Media.DATA, filePath);
// FileUtils.updateFile(filePath);
return cr.insert(IMAGE_URI, values);
}

Send the captured image to the web server in android

I want to send the captured image with the help of intent and send image to the remote server. I am using following code:
String image_str;
String URL =**************/image.php?;
ArrayList<NameValuePair> nameValuePairs;
imageview.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
TakePhoto();
}
});
private void TakePhoto() {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);
}
BitmapFactory.Options btmapOptions;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0 && resultCode == RESULT_OK) {
if (data != null) {
/* photo = (Bitmap) data.getExtras().get("data");
imageview.setImageBitmap(photo); *//* this is image view where you want to set image*/
Log.d("camera ---- > ", "" + data.getExtras().get("data"));
Toast.makeText(getApplicationContext(), getLastImageId(), Toast.LENGTH_LONG).show();
btmapOptions = new BitmapFactory.Options();
photo = BitmapFactory.decodeFile( getLastImageId(), btmapOptions);
imageview.setImageBitmap(photo);
}
// sendImg();
dialog = ProgressDialog.show(surakhaActivity.this, "", "Uploading file...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
}
});
sendImg();
// Toast.makeText(getBaseContext(), response, Toast.LENGTH_LONG).show();
}
}).start();
}
}
private String getLastImageId() {
final String[] imageColumns = { MediaStore.Images.Media._ID,
MediaStore.Images.Media.DATA };
final String imageOrderBy = MediaStore.Images.Media._ID + " DESC";
Cursor imageCursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageColumns,
null, null, imageOrderBy);
if (imageCursor.moveToFirst()) {
int id = imageCursor.getInt(imageCursor
.getColumnIndex(MediaStore.Images.Media._ID));
String fullPath = imageCursor.getString(imageCursor
.getColumnIndex(MediaStore.Images.Media.DATA));
imageCursor.close();
return fullPath;
} else {
return "no path";
}
}
InputStream inputStream;
File f;
public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException {
String res = "";
StringBuffer buffer = new StringBuffer();
inputStream = response.getEntity().getContent();
int contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
Toast.makeText(surakhaActivity.this, "contentLength : " + contentLength, Toast.LENGTH_LONG).show();
if (contentLength < 0) {
}
else {
byte[] data = new byte[512];
int len = 0;
try {
while (-1 != (len = inputStream.read(data)) ) {
buffer.append(new String(data, 0, len)); //converting to string and appending to stringbuffer…..
}
}
catch (IOException e) {
e.printStackTrace();
}
try {
inputStream.close(); // closing the stream…..
}
catch (IOException e) {
e.printStackTrace();
}
res = buffer.toString(); // converting stringbuffer to string…..
// Toast.makeText(MainActivity.this, "Result : " + res, Toast.LENGTH_LONG).show();
}
return res;
}
public void sendImg() {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
byte [] byte_arr = stream.toByteArray();
image_str = Base64.encodeBytes(byte_arr);
nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("imgdata",image_str));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
the_string_response = convertResponseToString(response);
// editor.putString("imgRes", the_string_response);editor.commit();
Toast.makeText(surakhaActivity.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();
}
catch(Exception e) {
Toast.makeText(surakhaActivity.this, "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show();
}
dialog.dismiss();
this.finish();
}
}
But capturing the image and send progress dialog runs infinite and image is not sent.
This looks fishy...
dialog = ProgressDialog.show(surakhaActivity.this, "", "Uploading file...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
}
});
sendImg();
// Toast.makeText(getBaseContext(), response, Toast.LENGTH_LONG).show();
}
}).start();
Can you put a "Log" on the sendImg() method to see if it ever gets called?

Categories