this is my method to post in server with two string and one image here i van send data correctly but when i send without image no data can be sent i want to send string and image in all cases with image and without image.
private void Posts()
{
final StringRequest stringRequest=new StringRequest(Request.Method.POST, uploadeImageUrl,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
String Response=jsonObject.getString("response");
Toast.makeText(Post.this,Response,Toast.LENGTH_LONG).show();
imagepost.setImageResource(0);
imagepost.setVisibility(View.GONE);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params =new HashMap<>();
params.put("name",editwriter.getText().toString().trim());
params.put("postcontent",editsubject.getText().toString().trim());
params.put("imagepost",imageToString(bitmap).trim());
return params;
}
};
Mysingletone.getInstance(Post.this).addToRequestque(stringRequest);
}
this is the code of imagetostring with method that get image
private void selectImages(){
Intent intent=new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,IMG_REQUEST);
}
private String imageToString(Bitmap bitmap)
{
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,100,byteArrayOutputStream);
byte[] imgbystes = byteArrayOutputStream.toByteArray();
return Base64.encodeToString(imgbystes,Base64.DEFAULT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==IMG_REQUEST&&resultCode==RESULT_OK&&data!=null) {
Uri path = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), path);
imagepost.setImageBitmap(bitmap);
imagepost.setVisibility(View.VISIBLE);
} catch (IOException e) {
e.printStackTrace();
}
}
}}
code of php in server .
$con= mysqli_connect($host_name,$user_name,$user_pass,$dp_name);
if($con)
{
date_default_timezone_set("Asia/Muscat");
$datee= date("Y/m/d");//strip_tags(trim($_POST["date"]));
$timee= date("h:i:sa");//strip_tags(trim($_POST["time"]));
$dt=date("Ymd");
$tm=date("his");
$name=$_POST['name'];
$postcontent=$_POST['postcontent'];
$image = $_POST["image"];
$imagepost= $_POST["imagepost"];
$rnd = rand(0, 5000);
$imgname="imagepost".$dt.$tm.$rnd.".jpg";
$url = "http://devsinai.com/DrSiani/imageUploadPostDr/images/".$imgname;
$sql="INSERT INTO posts (name,postcontent,imagepost) VALUE ('$name','$postcontent','$url')";
$sql2="INSERT INTO posts (name,postcontent,imagepost) VALUE ('$name','$postcontent')";
$uploads_path="images/$imgname";
if(mysqli_query($con,$sql))
{
file_put_contents($uploads_path,base64_decode($imagepost));
echo json_encode(array('response'=>'Successfully'));
}
else {
echo json_encode(array('response'=>'fiald'));
}
}
mysqli_close($con);
?>
Can you add the code of imageToString(Bitmap bitmap)?
Edit:
First of all add if statement to getParams() method like this:
String imageString = imageToString(bitmap);
if(!imageString.equals("false")){
params.put("imagepost",imageToString(bitmap).trim());
}
and let imageToString method return "false" as String when error.
Edit your php script like this:
$con= mysqli_connect($host_name,$user_name,$user_pass,$dp_name);
if($con){
date_default_timezone_set("Asia/Muscat");
$datee= date("Y/m/d");//strip_tags(trim($_POST["date"]));
$timee= date("h:i:sa");//strip_tags(trim($_POST["time"]));
$dt=date("Ymd");
$tm=date("his");
$name=$_POST['name'];
$postcontent=$_POST['postcontent'];
if(isset($_POST["image"])){
$imageChecker = TRUE;
$imagepost= $_POST["imagepost"];
$rnd = rand(0, 5000);
$imgname="imagepost".$dt.$tm.$rnd.".jpg";
$url = "http://devsinai.com/DrSiani/imageUploadPostDr/images/".$imgname;
$sql="INSERT INTO posts (name,postcontent,imagepost) VALUE ('$name','$postcontent','$url')";
} else {
$imageChecker = FALSE;
$sql="INSERT INTO posts (name,postcontent) VALUE ('$name','$postcontent')";
}
$uploads_path="images/$imgname";
if(mysqli_query($con,$sql)){
if($imageChecker)
file_put_contents($uploads_path,base64_decode($imagepost));
echo json_encode(array('response'=>'Successfully'));
} else {
echo json_encode(array('response'=>'fiald'));
}
}
mysqli_close($con);
Related
I am trying to get some data from a server. User clicks search and another acitivity starts by startActivityForResult().when user clicks the data the data should be put inside intent and setResult() is done with that intent and finish() is called. Now i have tried debugg but when finish() is called the activity does no go back to the one which called this activity. instead the app closes down.
Here is the code;
public class SearchContactActivity extends AppCompatActivity {
ProgressBar pb;
CircleImageView profile_image_search;
TextView name_search,user_name_search;
EditText edit_search_contact;
Button btn_search_contact;
ConstraintLayout cl;
String profile_image,firstName,lastName;
RequestQueue myQueue;
String url = "working url";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_contact);
pb = findViewById(R.id.progressBar);
profile_image_search = findViewById(R.id.profile_image_search);
name_search = findViewById(R.id.name_search);
user_name_search = findViewById(R.id.user_name_search);
btn_search_contact = findViewById(R.id.btn_search_contact);
edit_search_contact = findViewById(R.id.edit_search_contact);
cl = findViewById(R.id.nested_layout);
cl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setResultForPreviousAcitvity();
}
});
btn_search_contact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
search_contacts();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
hideVisibility();
}
public void setResultForPreviousAcitvity()
{
Intent data = new Intent();
data.putExtra("first_name",firstName);
data.putExtra("last_name",lastName);
data.putExtra("user_name",user_name_search.getText().toString());
data.putExtra("profile", profile_image);
setResult(RESULT_OK,data);
finish(); // app closes down here
}
private void search_contacts() throws JSONException {
pb.setVisibility(View.VISIBLE);
//send php data in json array format
//JSONObject jsonbody = new JSONObject("{\"search_key\":\"jhonsanders \"}");
HashMap<String, String> params = new HashMap<String, String>();
params.put("search_key", edit_search_contact.getText().toString().trim());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest( url,new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("result");
for(int i = 0; i < jsonArray.length(); i++)
{
JSONObject myobj = jsonArray.getJSONObject(i);
firstName = myobj.getString("first_name");
lastName = myobj.getString("last_name");
String userName = myobj.getString("user_name");
profile_image = myobj.getString("profile_image");
Bitmap image = NameAndImage.stringToImage(profile_image);
show_visibility();
profile_image_search.setImageBitmap(image);
user_name_search.setText(userName);
name_search.setText(firstName+" "+lastName);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
})/*{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> param = new HashMap<>();
param.put("search_key",edit_search_contact.getText().toString().trim());
return param;
}
}*/;
myQueue = VolleySingleton.getInstance(SearchContactActivity.this).getRequestQueue();
myQueue.add(jsonObjectRequest);
}
private void hideVisibility()
{
pb.setVisibility(View.INVISIBLE);
profile_image_search.setVisibility(View.INVISIBLE);
name_search.setVisibility(View.INVISIBLE);
user_name_search.setVisibility(View.INVISIBLE);
}
private void show_visibility()
{
profile_image_search.setVisibility(View.VISIBLE);
name_search.setVisibility(View.VISIBLE);
user_name_search.setVisibility(View.VISIBLE);
pb.setVisibility(View.INVISIBLE);
}
/* private Bitmap stringToImage(String s)
{
byte[] image = Base64.decode(s,Base64.DEFAULT);
Bitmap decodedImage = BitmapFactory.decodeByteArray(image,0,image.length);
return decodedImage;
}*/
}
The above activity is called by
Intent i = new Intent(ContactsActivity.this,SearchContactActivity.class);
startActivityForResult(i,REQUEST_CONTACT_SEARCH);
This is the manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.privatechat">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:theme="#style/Theme.PrivateChat">
<activity android:name=".SearchContactActivity"></activity>
<activity android:name=".ContactsActivity" />
<activity android:name=".NameAndImage" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<uses-library
android:name="org.apache.http.legacy"
android:required="false" />
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
There is no logs that i can print.The log is cleared when onfinish() is called.
The app goes back to this other activity. This one also has onAcitivityResult but its not the one that called the other acitivity.
public class NameAndImage extends AppCompatActivity {
EditText editFirstName,editLastName;
ImageView profile_image;
Button uploadNameImage;
Bitmap image;
RequestQueue myQueue;
SaveSharedPreference sp = new SaveSharedPreference();
private String URL = "working url";
public static final int PICK_IMAGE_REQUEST = 1011;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_name_and_image);
editFirstName = findViewById(R.id.edit_first_name);
editLastName = findViewById(R.id.edit_last_name);
profile_image = findViewById(R.id.profile_image_search);
uploadNameImage = findViewById(R.id.upload_name_image);
Log.i("SharedPreference",sp.getUserName(NameAndImage.this).trim());
profile_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pickPhoto();
}
});
uploadNameImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadData();
}
});
}
private void pickPhoto()
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent,PICK_IMAGE_REQUEST);
}
private void uploadData()
{
StringRequest upload_data = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response.trim().equals("success_data_upload"))
{
Toast.makeText(NameAndImage.this, "upload success", Toast.LENGTH_SHORT).show();
Intent i = new Intent(NameAndImage.this,ContactsActivity.class);
startActivity(i);
}
if(response.trim().equals("Error"))
{
Toast.makeText(NameAndImage.this, "upload error", Toast.LENGTH_SHORT).show();
Log.i("server",response.toString());
}
else
{
Toast.makeText(NameAndImage.this, "Response dont match", Toast.LENGTH_SHORT).show();
Log.i("server",response);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(NameAndImage.this, error.toString(), Toast.LENGTH_SHORT).show();
Log.i("server",error.toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> param = new HashMap<>();
param.put("image",imageToString(image));
param.put("first_name",editFirstName.getText().toString());
param.put("last_name",editLastName.getText().toString());
param.put("user_name",sp.getUserName(NameAndImage.this).trim());
return param;
}
};
upload_data.setRetryPolicy(new DefaultRetryPolicy(
3000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
));
myQueue = VolleySingleton.getInstance(NameAndImage.this).getRequestQueue();
myQueue.add(upload_data);
}
public static String imageToString(Bitmap pic)
{
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
pic.compress(Bitmap.CompressFormat.JPEG,100,byteArrayOutputStream);
byte[] imageByte = byteArrayOutputStream.toByteArray();
return Base64.encodeToString(imageByte,Base64.DEFAULT);
}
public static Bitmap stringToImage(String s)
{
byte[] image = Base64.decode(s,Base64.DEFAULT);
Bitmap decodedImage = BitmapFactory.decodeByteArray(image,0,image.length);
return decodedImage;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK)
{
Uri uri = data.getData();
try {
image = MediaStore.Images.Media.getBitmap(getContentResolver(),uri);
profile_image.setImageBitmap(image);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Edit:
The app seems to close but after 2 sec the wrong activity is started.
When setting the result in setResult() i was putting a string profile which contained image as a String. I guess the string was really large but when i debugg the whole string seemed to be there. So when i made profile empty the app operated normally. Looks like i will have to split the string in 2 for more effectiveness.
in fact I am in the process of preparing an android application that makes the upload of an image on a server thanks to a REST API.
I tested lapi with POSTMAN and I have no errors.
but have an error in this part: I that the crash app before intent
this is my source codes:
public class FileShooser extends AppCompatActivity {
private static final int INTENT_REQUEST_CODE = 100;
private String name ;
private CompositeSubscription mSubscriptions;
ProgressDialog progressdialog ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSubscriptions = new CompositeSubscription();
// get name from last activity
name= getIntent().getStringExtra("Name");
// start file shooser intent
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
try {
startActivityForResult(intent, INTENT_REQUEST_CODE );
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==INTENT_REQUEST_CODE)
{
if(resultCode==RESULT_OK){
uploadImage( data.getData());
}
}
}
public byte[] getBytes(InputStream is) throws IOException {
ByteArrayOutputStream byteBuff = new ByteArrayOutputStream();
int buffSize = 1024;
byte[] buff = new byte[buffSize];
int len = 0;
while ((len = is.read(buff)) != -1) {
byteBuff.write(buff, 0, len);
}
return byteBuff.toByteArray();
}
private void uploadImage(Uri fileUri) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitInterface retrofitInterface = retrofit.create(RetrofitInterface.class);
// use the FileUtils to get the actual file by uri
File file = new File(fileUri.getPath());
showSnackBarMessage("name:"+file.getName());
// create RequestBody instance from file
RequestBody requestFile =
RequestBody.create(
MediaType.parse(getContentResolver().getType(fileUri)),
file
);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body =
MultipartBody.Part.createFormData("image", file.getName(), requestFile);
// progress dialog
progressdialog = new ProgressDialog(getApplicationContext());
progressdialog.setMessage("Please wait ...");
progressdialog.show();
retrofitInterface.upload(name,body).observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(this::handleResponse,this::handleError);
}
private void handleError(Throwable error) {
progressdialog.dismiss();
if (error instanceof HttpException) {
Gson gson = new GsonBuilder().create();
try {
String errorBody = ((HttpException) error).response().errorBody().string();
Response response = gson.fromJson(errorBody,Response.class);
showSnackBarMessage(response.getMessage());
} catch (IOException e) {
e.printStackTrace();
}
} else {
showSnackBarMessage("Network Error !");
}
}
private void handleResponse(Response response) {
progressdialog.dismiss();
showSnackBarMessage(response.getMessage());
}
private void showSnackBarMessage(String message) {
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
}
thank you very much for your answers
I want to upload multiple images to server using multi-part, I didn't get proper code, anyone please help me to fix solve my problem.If i send as base64 format ,backend team cant able to get my image. Thats' why I go with multipart. Either Volley or Asynctask.
I tried this code from this link
https://www.simplifiedcoding.net/upload-image-to-server/
But multiple images I dont know how to do.
Main.Java
package com.getspot.getspot.imagerestapi;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main7);
findViewById(R.id.buttonUploadImage).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//if everything is ok we will open image chooser
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 100);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == RESULT_OK && data != null) {
//getting the image Uri
Uri imageUri = data.getData();
try {
//getting bitmap object from uri
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
//displaying selected image to imageview
imageView.setImageBitmap(bitmap);
//calling the method uploadBitmap to upload image
uploadBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public byte[] getFileDataFromDrawable(Bitmap bitmap) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 80, byteArrayOutputStream);
Log.i("AS","--"+byteArrayOutputStream.toByteArray());
return byteArrayOutputStream.toByteArray();
}
private void uploadBitmap(final Bitmap bitmap) {
//getting the tag from the edittext
final String tags = editTextTags.getText().toString().trim();
//our custom volley request
VolleyMultipartRequest volleyMultipartRequest = new VolleyMultipartRequest(Request.Method.POST, ServerUtils.Gs_Clock_Image,
new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
try {
JSONObject obj = new JSONObject(new String(response.data));
Log.i("AS","obj--"+obj);
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("AS","error--"+error);
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
/*
* If you want to add more parameters with the image
* you can do it here
* here we have only one parameter with the image
* which is tags
* */
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("gs_userId", "6");
return params;
}
/*
* Here we are passing image by renaming it with a unique name
* */
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
long imagename = System.currentTimeMillis();
Log.i("AS","imagename--"+imagename);
Log.i("AS","getFileDataFromDrawable(bitmap)--"+getFileDataFromDrawable(bitmap));
params.put("gs_task_image", new DataPart(imagename + ".png", getFileDataFromDrawable(bitmap)));
return params;
}
};
//adding the request to volley
Volley.newRequestQueue(this).add(volleyMultipartRequest);
}
}
Note:While passing the byte-array in gs_text_image,in that how can i send multiple images.I referred that above link.Please help me
I'll show you how I do it (particular case ofc, but it might give you an idea)
So, first of all you need the method interface which will look like this:
#Multipart
#POST(RestClient.UPLOAD_PICTURES_FOR_ORDER)
Call<YourTypeOfResponse> uploadPictures(#Part("images[]") RequestBody[] file, #Part MultipartBody.Part[] images);
now, you will have to prepare the files(images) that you have, for the request
private void multiparts(){
RequestBody reqFullPicFile;
MultipartBody.Part filepart;
RequestBody filename;
images = new MultipartBody.Part[files.size()];
filenameImages = new RequestBody[files.size()];
for (int file = 0; file < files.size(); file++){
reqFullPicFile = RequestBody.create(MediaType.parse("multipart/form-data"), files.get(file));
filepart = MultipartBody.Part.createFormData("full_picture", files.get(file).getName(), reqFullPicFile);
filename = RequestBody.create(MediaType.parse("text/plain"), files.get(file).getName());
images[file] = filepart;
filenameImages[file] = filename;
}
}
And, in the end, make the request with the created Multiparts (in this case images & filenameImages)
private void uploadPicturesReq(){
if (files != null) {
multiparts();
RestClient.getApi().uploadPictures(filenameImages, images)
.enqueue(new Callback<PicturesResponse>() {
#Override
public void onResponse(Call<PicturesResponse> call, Response<PicturesResponse> response) {
if (response.isSuccessful() && response.code() == 200) {
// here you can handle the response from server
}
}
#Override
public void onFailure(Call<PicturesResponse> call, Throwable t) {
Log.e(TAG, "-=onFailure=- " + t.getMessage(), t);
}
});
}
}
When I'm taking an image from gallery and want to insert into server, it puts the image with zero byte size. And in the table I have two columns, rollno and image. I get the rollno value from shared preference but it does not put the rollno in the database table, rollno column shows empty.
Help me to resolve this.
Here is my code
public class ImageEditActivity extends AppCompatActivity implements View.OnClickListener {
ImageView image;
Button btn_cancel_edit,btn_done_edit;
Bitmap bitmap;
SharedPreferences sp;
String rollno;
String KEY_Rollno = "rollno";
String KEY_IMAGE = "image";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_edit);
getSupportActionBar().hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
image=(ImageView)findViewById(R.id.image);
bitmap=ProfileActivity.bitmap;
image.setImageBitmap(bitmap);
btn_done_edit = (Button) findViewById(R.id.btn_done_edit);
btn_cancel_edit = (Button) findViewById(R.id.btn_cancel_edit);
btn_done_edit.setOnClickListener(this);
btn_cancel_edit.setOnClickListener(this);
sp=getSharedPreferences("rajput",MODE_PRIVATE);
rollno=sp.getString("rollno",null);
}
#Override
public void onClick(View v) {
if(v == btn_done_edit){
uploadImage();
}
if(v == btn_cancel_edit){
onBackPressed();
}
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
private void uploadImage() {
String UPLOAD_URL ="http://aptronnoida.com/applock/image_insert.php";
final ProgressDialog loading = ProgressDialog.show(this,"Uploading...","Please wait...",false,false);
StringRequest stringRequest = new StringRequest(Request.Method.GET, UPLOAD_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
//Disimissing the progress dialog
loading.dismiss();
//Showing toast message of the response
Toast.makeText(ImageEditActivity.this, s , Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//Dismissing the progress dialog
loading.dismiss();
//Showing toast
Toast.makeText(ImageEditActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Converting Bitmap to String
String image = getStringImage(bitmap);
//Creating parameters
Map<String,String> params = new Hashtable<String, String>();
//Adding parameters
params.put(KEY_Rollno,rollno);
params.put(KEY_IMAGE, image);
//returning parameters
return params;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
public void onBackPressed(){
super.finish();
}
}
Please try below working code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button buttonChoose;
private Button buttonUpload;
private ImageView imageView;
private EditText editTextName;
private Bitmap bitmap;
private int PICK_IMAGE_REQUEST = 1;
private String UPLOAD_URL = "http://coderzheaven.com/sample_file_upload/upload_image.php";
private String KEY_IMAGE = "image";
private String KEY_NAME = "name";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo);
buttonChoose = (Button) findViewById(R.id.buttonChoose);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
editTextName = (EditText) findViewById(R.id.editText);
imageView = (ImageView) findViewById(R.id.imageView);
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
}
public String getStringImage(Bitmap bmp) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
private void uploadImage() {
//Showing the progress dialog
final ProgressDialog loading = ProgressDialog.show(this, "Uploading...", "Please wait...", false, false);
StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
//Disimissing the progress dialog
loading.dismiss();
//Showing toast message of the response
Toast.makeText(MainActivity.this, s, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//Dismissing the progress dialog
loading.dismiss();
//Showing toast
Toast.makeText(MainActivity.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Converting Bitmap to String
String image = getStringImage(bitmap);
//Getting Image Name
String name = editTextName.getText().toString().trim();
//Creating parameters
Map<String, String> params = new Hashtable<String, String>();
//Adding parameters
params.put(KEY_IMAGE, image);
params.put("Roll_NO", "5");
//returning parameters
return params;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
//Getting the Bitmap from Gallery
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting the Bitmap to ImageView
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onClick(View v) {
if (v == buttonChoose) {
showFileChooser();
}
if (v == buttonUpload) {
uploadImage();
}
}
}
Reference source: http://www.coderzheaven.com/2011/04/25/android-upload-an-image-to-a-server/
Try changing it to PNG and reduce the compression in the following line
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
To
bmp.compress(Bitmap.CompressFormat.PNG, 80, baos);
I am developing a project where user store some information and image into SQLite database. The image is stored as BLOB data. Now I want to upload all data into my MySQL database. I am using Volley to upload all rows one by one from SQLite to MySQL server with a AsyncTask calling a Web API.
Everything working fine without the image BLOB data. I do not know is there any way to upload blob data using Volley.
I have search a lot into StackOverflow but did not get any solution, please help me.
I am giving some code example to make my question better understandable.
Here is my function calling in a AsyncTask:
/**
* function to upload data into server
* */
private void SyncTaskDoInBack(final dataDB data) {
// Tag used to cancel the request
String tag_string_req = "Inserting Online";
StringRequest strReq = new StringRequest(Method.POST, AppConfig.API_LINK, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
Log.d(TAG, "Success");
} else {
// Error in found
String errorMsg = jObj.getString("error_msg");
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("ID", data._id);
params.put("PersonName", data.pName);
params.put("Photo", data.photo.toString());
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
My "dataDB" Class is as follows:
public class dataDB implements Comparable<dataDB>{
String _id = null;
String pName = null;
byte[] photo = null;
#Override
public int compareTo(dataDB o) {
//return title.toLowerCase().compareTo(o.title.toLowerCase());
return 0;
}
}
List Data Model class is follows:
public class ListDataModel {
private int _id;
private String name;
private byte[] image;
public ListDataModel() { }
public ListDataModel(String name, String thumbnailUrl) {
this.name = name;
this.thumbnailUrl = thumbnailUrl;
}
// getting ID
public int getID() {
return this._id;
}
// setting id
public void setID(int keyId) {
this._id = keyId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public byte[] getImage() {
return this.image;
}
public void setImage(byte[] image) {
this.image = image;
}
}
After searching a lot into StackOverflow, I have come up with the following formula, which appears to produce the camera image into Base64 String and Vice-versa. Hope this will help others.
I am using Apache Commons Codec for Base64 encode/decode from here http://commons.apache.org/proper/commons-codec/ (I think one can use Android default Base64 class too, I am using this for other purposes also)
Here is my onActivityResult function
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case CAMERA_REQUEST:
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap myImage = extras.getParcelable("data");
ByteArrayOutputStream bao = new ByteArrayOutputStream();
myImage.compress(Bitmap.CompressFormat.JPEG, 90, bao);
imageInByte = bao.toByteArray();
imageInBase64Str = Base64.encodeBytes(imageInByte); // using internal class
}
break;
}
}
Then I'm passing the Base64 String imageInBase64Str to my insert statement of SQlite and MySQL online database.
When getting image Base64 encoded data from SQLite or MySQL to view, I'm processing my image like the following way:
try {
byte[] decodedByte = Base64.decode(imageData, 0);
theImage = BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
}catch (IOException io){
Log.d("ViewRecord",io.getMessage());
}
That's it :)