How to delete already uploaded image file from server? - android

I created image uploading through a XAMPP server using PHP. But I need to
know how to delete the uploaded image file from Android. How can I do that?
php file(upload) :
<?PHP
if(isset($_POST['image'])){
$now = DateTime::createFromFormat('U.u', microtime(true));
$id = $now->format('YmdHisu');
$upload_folder = "upload/";
$path = "$upload_folder/$id.jpeg";
$image = $_POST['image'];
if(file_put_contents($path, base64_decode($image)) != false){
echo "uploaded_success";
exit;
}
else
{
echo "Sorry, your file is too large.";
echo "upload_failed";
exit;
}
}
else{
echo "image_not_in";
exit;
}
?>

You can get the photo path and delete it in the successful response from the server!
make sure you declare permission in the manifest!
<uses-permission> android:name="android.permission.WRITE_INTERNAL_STORAGE" />
in you code..
PostResponseAsyncTask task = new PostResponseAsyncTask(MainActivity.this, postData, new AsyncResponse() {
#Override
public void processFinish(String s) {
if (s.contains("uploaded_success")) {
File photoDelete = new File(selectedPhoto);
if (photoDelete.exists()) {
if (photoDelete.delete()) {
Log.d("DELETE", "deleted:" + selectedPhoto);
}
}
Toast.makeText(getApplicationContext(), "Image Uploaded Successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Error while uploading...", Toast.LENGTH_SHORT).show();
}
}
});

You can delete an image from your server by sending a command from your app (client) to the server asking the server to delete the file from its local storage.
Let's say you set the imageName of your image file to to hashmap to send to the server by:
HashMap<String, String> postData = new HashMap<String, String>();
postData.put("deleteImage", imageName);
and execute it:
task.execute("http://192.168.1.7/news/delete.php");
Now, you just need to see if the value of the deleteImage is set or not (on your server, in the delete.php file) by and delete the file by calling unlink method in PHP:
Delete.php
<?PHP
if(isset($_POST['deleteImage'])){
$imageName = $_POST['deleteImage'];
unlink($imageName) //this deletes the image file
}
?>

Related

I cannot identify what is causing this unexpected upload error on my app

I am relatively new to android development and I have been squeezing my brain juice for hours on probably a very simple error. Look, the app's been working fine yesterday and after I made some changes on some XML files and ran the app on my emulator, I experience this error:
2019-09-10 14:13:19.533 6388-
6516/ E/Volley: [301]
BasicNetwork.performRequest: Unexpected response code 406 for
http://applybpojobs.com/widevalueappfiles/server/api/addvehicle.php
2019-09-10 14:13:21.573 1633-1656/system_process E/memtrack: Couldn't load
memtrack module
I have already tried numerous solutions on the web and it seems not to fix my problem. This is my code:
StringRequest stringRequest = new StringRequest(Request.Method.POST,
URL_ADD_VEHICLE,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i(TAG, response.toString());
try {
JSONObject jsonObject = new JSONObject(response);
String Success = jsonObject.getString("success");
if (Success.equals("1")){
hideLoader();
Toast.makeText(Addvehicle.this,"Vehicle Added
Successfully",Toast.LENGTH_SHORT).show();
}else if (Success.equals("0")){
hideLoader();
Toast.makeText(Addvehicle.this,"Vehicle
Already Exist",Toast.LENGTH_SHORT).show();
}
}catch (JSONException e){
e.printStackTrace();
hideLoader();
Toast.makeText(Addvehicle.this,"Vehicle Added
Error"+e.toString(),Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
Toast.makeText(Addvehicle.this,"Vehicle Added
Error"+error.toString(),Toast.LENGTH_SHORT).show();
hideLoader();
}
})
I am receiving a blank response from this URL and I need guidance on how to fix this:
http://*********.php
For whatever reasons, this page on my app stopped working because of this error. Any help would be appreciated. Again, I'm basically new in android development so please understand that a simple error like this bleeds my nose.
Here are my server php codes:
<?php
require '../core/connect.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$plate_number=$_POST['plate_number'];
$vin=$_POST['vin'];
$car_make=$_POST['car_make'];
$car_model=$_POST['car_model'];
$car_year=$_POST['car_year'];
$displacement=$_POST['displacement'];
$fuel_type=$_POST['fuel_type'];
$transmission=$_POST['transmission'];
$mileage=$_POST['mileage'];
$owner_name=$_POST['owner_name'];
$address=$_POST['address'];
$phone_number=$_POST['phone_number'];
$email_adress=$_POST['email_adress'];
$facebook=$_POST['facebook'];
$adddate = date("d/m/Y");
$photo = $_POST['photo'];
$id=uniqid();
$path = "vehicle_upload/$id.jpeg";
$finalpath = "*********.$path;
$sql1=mysqli_query($connect,"SELECT * FROM _addvehicle WHERE
PlateNumber='$plate_number'");
if (mysqli_num_rows($sql1) > 0) {
$result['success'] = "0";
$result['message'] = "error";
echo json_encode($result);
}else{
$sql = mysqli_query($connect, "INSERT IGNORE INTO
_addvehicle(PlateNumber, Vin, Make, Model, Year, Displacement, FuelType,
Transmission, Mileage, OwnerorCompany, HomeorCompanyAddress, ContactNumber,
EmailAddress, FacebookID, AddDate, vehicleImage)VALUES('$plate_number','$vin','$car_make','$car_model','$car_year','$displacement','$fuel_type','$transmission','$mileage','$owner_name','$address','$phone_number','$email_adress','$facebook','$adddate','$finalpath')");
if ($sql) {
if (file_put_contents($path, base64_decode($photo))) {
$result['success'] = "1";
$result['message'] = "success";
echo json_encode($result);
//mysqli_close($connect);
}
}
}
}
?>
In POST request you need to send parameters like an empty Hashmap i.e
{"":""} or you need to try https instead of http.

Upload image server using multipart in android

Upload image server using multipart in android. Here i have used this url
public static final String UPLOAD_URL = "http://abcds.com/clients/cupidapi/uploadimg";
Here i have used multipart to upload image in Mysql database server. When i try to upload image on server, it shows notification in my device saying "Upload successfully" but there is no image record uploaded in database.
public void uploadMultipart() {
//getting the actual path of the image
String path = getPath(filePath);
Log.e(TAG,"PATH---------->"+path);
//Uploading code
try {
String uploadId = UUID.randomUUID().toString();
Log.e(TAG,"UPLOADID-------->"+uploadId);
//Creating a multi part request
new MultipartUploadRequest(this, uploadId,UPLOAD_URL)
.addFileToUpload( "image",path) //Adding file
.addParameter("name", name) //Adding text parameter to the request
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload(); //Starting the upload
Log.e(TAG,"URL----->"+path);
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
Log.e(TAG,"GETMESSAGE"+exc.getMessage());
}
}
the content I get logged looks like this:
03-20 13:42:28.316 12069-12089/com.example.uploadimageserver E/[DRVB][EXT][UTIL]: disp_only_chk: DRVB CHECK DISP PROCESS DONE ! (1/0x2f/0x30/0x2e)
03-20 13:42:28.316 12069-12089/com.example.uploadimageserver E/[DRVB][EXT][UTIL]: disp_only_chk: DRVB CHECK DISP PROCESS DONE ! (0/0/0)
03-20 13:46:44.656 12069-12069/com.example.uploadimageserver E/MainActivity: PATH---------->/storage/emulated/0/Pictures/Instagram/IMG_20190218_082042_666.jpg
03-20 13:46:44.691 12069-12069/com.example.uploadimageserver E/MainActivity: UPLOADID-------->35020ace-11aa-40cc-b0f4-50ec2879b9bd
03-20 13:46:44.745 12069-12069/com.example.uploadimageserver E/MainActivity: URL----->/storage/emulated/0/Pictures/Instagram/IMG_20190218_082042_666.jpg
Here my server code:
private function uploadimg(){
$currentDir = getcwd();
$uploadDirectory = "profile/";
$errors = []; // Store all foreseen and unforseen errors here
$fileExtensions = ['jpeg','jpg','png','gif']; // Get all the file extensions
$userid =$_POST['user_id'];
$fileName = $_FILES['images']['name'];
$fileSize = $_FILES['images']['size'];
$fileTmpName = $_FILES['images']['tmp_name'];
$fileType = $_FILES['images']['type'];
$fileExtension = strtolower(end(explode('.',$fileName)));
$uploadPath = $currentDir . $uploadDirectory . basename($fileName);
$uploadPath = $uploadDirectory . basename($fileName);
$imgurl="https://abcds.com/clients/cupidapi/".$uploadDirectory.$fileName ;
if (isset($_POST['name'])) {
if (! in_array($fileExtension,$fileExtensions)) {
$errors[] = "This file extension is not allowed. Please upload a JPEG or PNG file";
}
if ($fileSize > 2000000) {
$errors[] = "This file is more than 2MB. Sorry, it has to be less than or equal to 2MB";
}
if (empty($errors)) {
$didUpload = move_uploaded_file($fileTmpName, $uploadPath);
if ($didUpload) {
$success[] = "profile upload successfuly";
$sql ="INSERT INTO db_images(image_path,user_id) VALUES('$imgurl','$userid')";
$res=mysql_query($sql);
} else {
$errors[] = "An error occurred somewhere. Try again or contact the admin";
}
} else {
foreach ($errors as $error) {
$errors[] = $error . "These are the errors" . "\n";
}
}
}else{
$re="inserting problem....";
print(json_encode($re));
}
if(!$res)
{
$re="inserting problem....";
print(json_encode($re));
}
else{
$re="inserting success....";
print(json_encode($success));
}
}
Try to this example it is very good and easy to upload image file without any stretch image.
// Upload File
def uploadServiceVersion = "3.4.2"
implementation "net.gotev:uploadservice:$uploadServiceVersion"
Goto GitHub then see the code
https://github.com/gotev/android-upload-service/wiki/Setup

How to send image file to server - Kotlin using Fuel

I have a problem when attempting to use Fuel to send image to my server.
I am trying to use the Fuel.upload method.
Fuel.upload(urlfile).source { request, url ->
File(photopath)
}.responseString { request, response, result ->
}
the image is like : /storage/emulated/0/Android/data/fr.tais.riodi/files/Pictures/MyPicture4945313277123614993.jpg
$target_dir = "images/";
$target_file_name = $target_dir .basename($_FILES["file"]["name"]);
$response = array();
// Check if image file is a actual image or fake image
if (isset($_FILES["file"]))
{
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file_name))
{
$success = true;
$message = "Successfully Uploaded";
}
else
{
$success = false;
$message = "Error while uploading";
}
}
else
{
$success = false;
$message = "Required Field Missing";
}
$response["success"] = $success;
$response["message"] = $message;
echo json_encode($response);
I tried to find an example of this operation. Have you an examples or an idea?
Thanks all

How to retrieve particular row data from mysql through android Volley or JSON?

Hi guys i have already made login and register using volley library and data gets saved successfully as shown in the snap 1 below. Now my question is how to retrieve particular or specific row data for the particular user when he/she logins?? For example if user admin gets logged in how to fetch her entire row alone
saved data in server side
<?php
$conn = mysql_connect("localhost", "root", "");
if(isset($conn))
{
mysql_select_db('your_db', $conn);
}
else
{
echo 'Sorry,can not connect to database' ;
}
$userid = isset($_GET['id']) ? mysql_real_escape_string($_GET['id']) : "";
$qur = mysql_query("select usename,other_fields from `your_tbl` where userid= $userid");
$result =array();
while($r = mysql_fetch_array($qur)){
extract($r);
$result[] = array("usename" => $usename,"other_fields" => $other_fields);
}
$json =array("data"=>$result);
mysql_close($conn);
/* Output header */
header('Content-type: application/json');
echo json_encode($json);
You will have to use server side scripting. Webservice that will fetch that particular row of data.
The script should take your input parameters and give you the out put in Json Array or Object.
You then hit this script using volley and the response you receive can then be utilized for the next step.
//call volley get method and get data in success method
public void onSuccess(string response)
{
try {
String s = new String(response);
JSONObject jsonObject = new JSONObject(s);
if (jsonObject.has("data")) {
JSONArray country =jsonObject.getJSONArray("data");
for (int i = 0; i < country.length(); i++) {
JSONObject cnt = country.getJSONObject(i);
String res=cnt.getString("username"));
//now you can use res as per your requirement
}
} catch (JSONException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}

Android Studio Login/Register System ideas

I want to make a diet helper app for android devices, using android studio and
I need ideas on what to use to implement the login/register system, I followed a tutorial on youtube but it was outdated and I ended up wasting my time, then I've read on google, that android studio has a library called volley that I can use with PHP and MySql to make the login system.
Do you have other ideas, or is that the best one to go with?
I'm open to suggestions so shoot!
Update:
I've created a post about how to do this using a PHP backend for your Android application. https://keithweaver.ca/posts/4/android-php-custom-login
Additionally to the link above, this is how you can setup a server.
https://github.com/kweaver00/tutorials/blob/master/setup-server.md
https://keithweaver.ca/posts/9/setup-ubuntu-server-quickly
Original Post:
This is one solution and isn't guaranteed to be the best.
You can really use anything to communicate with a server. Async Tasks or Retrofit are both popular.
Assuming you have set up a server with a LAMP stack. Make sure you have an SSL so you don't pass user information that isn't encrypted.
Create a user table in mysql
Ex.
id int default->NULL AI primary-key
user varchar 250 default->null
pass varchar 250 default->null
signupdate date default-> null
Create a log in sessions table of some sort
Ex.
id int default->NULL AI primary-key
user varchar 250 default->null
token varchar 250 default->null
addedDate date default->null
Create a log in php script (I know this probably isnt the best way to right php code)
$connection = mysqli_connect("localhost", "phpmysqluser", "password", "dbname") or die("Error 404: unable to connect");
$username = $_POST['user'];
$pass = $_POST['pass'];
//add code to remove slashes and etc.
$result = mysqli_query($connection, "SELECT * FROM userTable WHERE user='$username' AND pass='$pass'") or die("Error: this line has error");
class response{
public $loggedin =0;
public $message = "";
}
$response = new response();
if(mysqli_num_rows($result) == 1){
$logInToken = generateLogInToken();
//have a function that creates a unique token and stores it for X days or minutes
$response->loggedin = 1;
$response->message = $logInToken;
}else{
$response->message = "wrong info";
}
echo json_decode($response);
This should output a json file like this depending on your user and pass variables.
{
"loggedin" : 1,
"message" : "asdnlansdkansd"
}
Right another script that passes in the log in token and user name to check if it's valid.
$connection .... //same as above
//well it really should be a include_once cause if you change credentials
$token = $_POST['token'];
$user = $_POST['user'];
$registeredDate = "";
$today = date('Y-m-d');
$result = mysqli_query($connection, "SELECT * FROM tokenTable WHERE user='$user' AND token='$token'") or die("Error...");
class response{
public $status = 0;
}
$response = new response();
if(mysqli_num_rows($result) == 1){
//check token has been register today and if not sign them out
while($row = mysqli_fetch_array($result)){
$registeredDate = $row['addedDate'];
}
if($registeredDate == $today){
//token is valid
$response->status = 3;
}else{
//expired
$response->status = 2;
}
}else{
//user and token are not valid
$response->status = 1;
}
echo json_decode($response);
Giving a json object like:
{
"status" : 3
}
In your Android app on open, run the code to check if the account is valid if there is anything stored locally. Or just go to log in screen.
On splash screen in the onCreate (you dont need a splash screen, its actually not recommended but its the easiest way to explain the process):
if(userNameAndTokenStoredInSharedPref()){
String token = getTokenFromSharedPref();
String userName = getUserNameFromSharedPref();
checkAgainstServer(token, userName);
}else{
Intent openLogInWindow = new Intent(this, LogInActivity.class);
startActivity(openLogInWindow);
}
still in the slash activity but out of the oncreate:
protected void checkAgainstServer(String token, String user){
//using retrofit
ThisAppRestClient.get().postCheckTokenAndUser(token, user, new Callback<UserStatusCallBack>() {
#Override
public void success(UserStatusCallBack userStatusCallback, retrofit.client.Response response) {
if(userStatusCallback.getStatus() == 1){
//Invalid token
}else if(userStatusCallback.getStatus() == 2){
//Expired token
}else if(userStatusCallback.getStatus() == 3){
//Success
Intent openMainWindow = new Intent(this, MainActivity.class);
startActivity(openMainWindow);
}
}
#Override
public void failure(RetrofitError error) {
//Retrofit errors like timeouts, etc.
}
}
}
The log in activity would be something like:
logBtn.setOnClickListener(new View.onClick...
String userName = userNameEditText.getText().toString().toLowerCase().trim();
String password = passwordEditText.getText().toString().trim();
if(!TextUtils.isEmpty(userName) && !TextUtils.isEmpty(password)){
callServerLogInScript(userName, password);
}
userNameEditText.setText("");
logBtn.setVisibility(View.GONE);
}
lower down the file:
protected void callServerLogInScript(String user, String pass){
//using retrofit
ThisAppRestClient.get().postCheckTokenAndUser(user, pass, new Callback<LogInCallBack>() {
#Override
public void success(LogInCallBack logInCallback, retrofit.client.Response response) {
if(logInCallback.getLoggedIn() == 1){
//succssful
storeUserNameInSharedPref(user);
storeTokenInSharedPref(logInCallback.getMessage());
Intent openMainActivity = new Intent(this, MainActivity.class);
startActivity(openMainActivity);
}else{
//incorrect log in
logBtn.setVisibility(View.VISIBLE);
}
}
#Override
public void failure(RetrofitError error) {
//Retrofit errors like timeouts, etc.
}
}
}
The reason for not storing the user name and password directly is if the device is rooted they can manipulate the data locally but not on your server.
It depends which you want to use. If you have your own server to host, then use php,mysql. If not, you can also use other third party which provides you to add if you know php,mysql to create.
Another option is if you don't want to use php mysql to store datas, then you can proceed with parse.com
So if you want to use parse.com, just register it. It's free to use.
Hope it will match your requirement, say for eg: if you want to create registration(everything saving in datas will be handled),you need to give exact object name that matches what you given in parse.com
Even you can also create in code itself without object name. I will show you a piece of example how to create and insert for registration..
ParseUser user = new ParseUser();
user.setEmail((txtEmail));//create an edittext and get the values in strings and store..
user.setPassword(txtPassword);//same for password
user.setUsername(txtUsername);//username
user.signUpInBackground(new SignUpCallback() {
public void done(ParseException e) {
if (e == null) {
//completed..it has been registered
Toast.makeText(getApplicationContext(),
"Successfully Signed up, please log in.",
Toast.LENGTH_LONG).show();
finish();
} else {
Toast.makeText(getApplicationContext(),
"Sign up Error", Toast.LENGTH_LONG)
.show();
}
}
});
Simple one if you don't want to use php,mysql. Well documentation and easy to integrate and use it. Happy coding.
FYI: Android studio is IDE for development. And volley is HTTP library that makes networking for Android.

Categories

Resources