How to upload Image php and mysql database Server Using Volley in Android studio
Uploading an image to a PHP and MySQL server using Volley in Android Studio is a common task in app development. To achieve this, follow these steps:
-
Add the Volley library to your project.
-
Create a PHP script that accepts the image and saves it to the server.
-
Create a Volley multipart request and attach the image file to it.
-
Send the request to the server using the Volley library.
-
Handle the server response and display a message to the user.
When creating the multipart request, make sure to set the content type to multipart/form-data and add a parameter for the file with its name and path. In the PHP script, use the $_FILES array to retrieve the file and its details and move it to a specified location.
Uploading images to a server is a useful feature in many apps, and using Volley makes the process easier and more efficient.
xml code: use into your layout like LinearLayout
<de.hdodenhof.circleimageview.CircleImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/profile_image"
android:layout_width="96dp"
android:layout_height="96dp"
android:layout_marginTop="30dp"
android:layout_gravity="center_horizontal"
android:src="@drawable/img"
app:civ_border_width="2dp"
app:civ_border_color="#EF1B1B"/>
<soup.neumorphism.NeumorphImageButton
android:id="@+id/uploadImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/plus"
android:layout_gravity="top|center"/>
use dependencies
implementation 'de.hdodenhof:circleimageview:3.1.0'
implementation 'com.github.bumptech.glide:glide:4.12.0'
AndroidMainFest.xml permission for upload image in your phone
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Declear Variable
NeumorphImageButton uploadImage;
private String imageData;
CircleImageView profile_image;
Java Code:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
addToCarts = new AddToCarts();
View root = inflater.inflate(R.layout.fragment_user_profile, container, false);
//Im use SessionManager for Get Data After Login you can use Model and Adapter
sessionManager = new SessionManager(getContext());
profile_image =root.findViewById(R.id.profile_image);
btnSave =root.findViewById(R.id.btnSave);
uploadImage =root.findViewById(R.id.uploadImage);
if(sessionManager.getLogin()){
HashMap<String, String> user = sessionManager.getUserDetail();
USERIMAGE = user.get(sessionManager.USERIMAGE);
Glide.with(getContext())
.load(USERIMAGE)// use your URL link or getImage and setImage
.placeholder(R.drawable.profile)
.error(R.drawable.img) // if your image not upload into databaes then show this image
.into(profile_image);
btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(UserNameFullN.getText().toString().isEmpty() || userEmailPro.getText().toString().isEmpty()||userAddressPro.getText().toString().isEmpty()){
Toast.makeText(getActivity(), "দয়া করে আবার চেষ্টার করুন। ধন্যবাদ", Toast.LENGTH_SHORT).show();
}else{
SaveToUserDB();
}
}
});
}
///////// this code for image upload button
uploadImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, REQUEST_CODE);
} catch (Exception e) {
e.printStackTrace();
}
}
});
return root;
}
///////// this code save image upload
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) {
if (data != null && data.getData() != null) {
Uri imageUri = data.getData();
try {
imageData = getBase64Image(imageUri);
// Call your API or do whatever you need to do with the Base64-encoded image data
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
public String getBase64Image(Uri imageUri) throws FileNotFoundException {
ContentResolver contentResolver = getActivity().getContentResolver();
InputStream inputStream = contentResolver.openInputStream(imageUri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
byte[] byteArray = stream.toByteArray();
// Encode the byte array as a base64 string
String base64String = Base64.encodeToString(byteArray, Base64.DEFAULT);
return base64String;
}
public void SaveToUserDB(){
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("এ্যকাউন্টটি তৈরী হচ্ছে, দয়াকরে কিছুক্ষণ অপেক্ষা করুন। ধন্যবাদ");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST,"https://www.yourdomain.com/json.php",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
progressDialog.dismiss();
Toast.makeText(getActivity(), "আপনার এ্যাকাউন্ট আপডেট করা হয়েছে। দয়া করে আবার লগইন করুন। ধন্যবাদ", Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getActivity(), "আপনার ইন্টারনেট সংযোগটি হইতো বিছন্ন আছে, দয়া করে আবার চেষ্টার করুন। ধন্যবাদ", Toast.LENGTH_SHORT).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("UserImage", imageData);
return params;
}
};
VolleySingleton.getInstance(getActivity()).addToRequestQueue(stringRequest);
}
}
Php Code:
<?php
$conn = mysqli_connect("localhost","username","password","bdname);
$conn->set_charset("utf8");
mysqli_query('SET CHARACTER SET utf8');
mysqli_query("SET SESSION collation_connection ='utf8_unicode_ci'");
if($conn){
$UserImage = $_POST['UserImage'];
$imageData = base64_decode($UserImage);
// Generate a unique filename for the image
$filename = uniqid() . ".png";
// Save the image to disk
file_put_contents("../UserImage/" . $filename, $imageData);
$query = "INSERT INTO tbl_name(UserImage) VALUES('https://yourdomain.com/foldername/".$filename."')";
$result = mysqli_query($conn,$query);
if($result)
{
$status='OK';
}
else {
$status ='FAILED';
}
}
else {
$status='FAILED';
}
echo json_encode(array("response"=>$status));
mysqli_close($con);
?>