Image Uploading from android application to Server is not working - php

I'm developing an android app which requires to upload the image taken with camera to the server. I used a tutorial for this and imported the project
from this link, refer this for android code
My PHP file which is indicating success of the image and returning me the URL but the image is not found on the server. I am not able to troubleshoot this problem.
My PHP file code is:
<?php
// Path to move uploaded files
$target_path = "Upload_image_ANDROID/";
// array for final json respone
$response = array();
// getting server ip address
$server_ip = '216.86.147.200';
// final file url that is being uploaded
$file_upload_url = 'http://' . $server_ip . '/' . 'sss_api' . '/' . $target_path;
if (isset($_FILES['image']['name'])) {
$target_path = $target_path . basename($_FILES['image']['name']);
// reading other post parameters
// $email = isset($_POST['email']) ? $_POST['email'] : '';
//$website = isset($_POST['website']) ? $_POST['website'] : '';
$response['file_name'] = basename($_FILES['image']['name']);
//$response['email'] = $email;
//$response['website'] = $website;
try {
// Throws exception incase file is not being moved
if (!move_uploaded_file($_FILES['image']['tmp_name'], $target_path)) {
// make error flag true
$response['error'] = true;
$response['message'] = 'Could not move the file!';
}
// File successfully uploaded
$response['message'] = 'File uploaded successfully!';
$response['error'] = false;
$response['file_path'] = $file_upload_url . basename($_FILES['image']['name']);
} catch (Exception $e) {
// Exception occurred. Make error flag true
$response['error'] = true;
$response['message'] = $e->getMessage();
}
} else {
// File parameter is missing
$response['error'] = true;
$response['message'] = 'Not received any file!F';
}
// Echo final json response to client
echo json_encode($response);
?>

If you follow the tutorial to the end and your Android App is working as expected on your device, the problem is more on the server side due to permission, your server doesn't allow you to save the file.
Try to set the location to a folder where your application will have permission to write to or change htaccess you can get more info on http://httpd.apache.org/docs/2.2/howto/htaccess.html

Related

Send a image from android via Post method to PHP and save it in server?

I am written an android app that should send profile images to server and save it there ...
I am using gotev android upload service and it works well and send my image to server , but my problem is in my server side that can't move or copy of it in my destination folder ...
my PHP in my server is :
<?php
$isSuccess = false ;
$uploaddir = 'profiles/';
$uploadfile = $uploaddir . basename($_FILES['profile']['name']);
if ($_FILES["profile"]["error"] > 0) {
echo "Error: " . $_FILES["profile"]["error"] . "<br>";
} else {
$myObj->name = $_FILES['profile']['name'];
$myObj->type = $_FILES['profile']['type'];
$myObj->size = ($_FILES["profile"]["size"] / 1024);
$myObj->storedin = $_FILES['profile']['tmp_name'];
$myObj->username = $_POST['username'];
if(isset($_FILES['profile']['name']) && isset($_POST['username'])){
try{
copy($_FILES['profile']['tmp_name'],$uploadfile );
//$movesuc = move_uploaded_file($_FILES['profile']['tmp_name'],$uploadfile);
//$myObj->mvesuc = $movesuc;
$myObj->error = false;
$isSuccess = true;
$myObj->message = 'File uploaded successfully';
}catch(Exception $e){
$myObj->error = true;
$myObj->message = 'Could not upload file';
}
}else{
$myObj->error = true;
$myObj->message = "Required params not available";
}
}
//header('Content-Type: application/json');
$myObj->isSuccess = $isSuccess;
$myJSON = json_encode($myObj);
echo $myJSON;

PHP move_uploaded_file fail

I am trying to upload an image through alamofire and I have done it! My server received it but when I call move_uploaded_file function in my php file it shows FAILURE. I am sure that my server received the image and i am able to create directories through php. It is just this move_uploaded_file not letting me do the job. Here is my php code:
<?php
if (empty($_FILES["image"])){
$response = array("error" => "no data");
}else{
$path = "./Upload";
if(!file_exists($path)){
mkdir($path,0777,true);
$response["message"] = "new file created";
}else{
$response["message"] = "file already exist";
if(move_uploaded_file($_FILES["image"]["tmp_name"],$path)){
$response["message"] = "You've got it!!!";
}else{
$response["message"] = "upload function fail";
}
}
}
echo json_encode($response);
?>
$path is a directory, not a file. Change it to:
$path = "./Upload/file.txt";
Change:
$path = "./Upload";
With:
$path= "uploads/" . basename($_FILES["fileToUpload"]["name"]);

uploading file from android app into desired folder

I wan to upload file from android app using PHP in specific folder below is the code which I have tried.
pleas help me what is wrong in this code and please suggest me some easy solution for this or is this method right to upload files from android app on serever
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
//checking the required parameters from the request
if(isset($_POST['exp']) && isset($_POST['employee_id']) && isset($_FILES['pdf']['name']) ){
//connecting to the database
$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASSWORD,DB_DATABASE) or die('Unable to Connect...');
$resume_name = $_POST['exp'];
$employee_id = $_POST['employee_id'];
$file_data = $_FILES['pdf']['name'];
$upload_path = 'Images/Employee_Profile_Picture/'.$employee_id.'/Resume/';
//getting file info from the request
$fileinfo = pathinfo($_FILES['pdf']['name']);
//getting the file extension
$extension = $fileinfo['extension'];
//file url to store in the database
$file_url = $upload_path . getFileName($employee_id). '.'. $extension;
//file path to upload in the server
$file_path = $upload_path . getFileName($employee_id);
try{
if(file_exists($upload_path))
{
$existing_file = glob($upload_path."/*.*");
$empty_file = implode(" ",$existing_file);
move_uploaded_file($_FILES['pdf']['name'],$upload_path) ;
$sql = "UPDATE employee_registration SET resume_name ='$resume_name', resume_path='$file_url' where employee_id ='$employee_id'";
//adding the path and name to database
if(mysqli_query($con,$sql)){
//filling response array with values
$response['Success'] = "File Uploaded Successfully...!";
echo json_encode($response);
}
else
{
$response['Error'] = "File Uploading Error...!";
echo json_encode($response);
}
}
else
{
mkdir('Images/Employee_Profile_Picture/'.$employee_id.'/Resume');
move_uploaded_file($_FILES['pdf']['name'],$upload_path) ;
$sql = "UPDATE employee_registration SET resume_name ='$resume_name', resume_path='$file_url' where employee_id ='$employee_id'";
//adding the path and name to database
if(mysqli_query($con,$sql))
{
//filling response array with values
$response['Success'] = "File Uploaded Successfully...!";
echo json_encode($response);
}
else
{
$response['Error'] = "File Uploading Error...!";
echo json_encode($response);
}
}
}catch(Exception $e){
$response['error']=true;
$response['message']=$e->getMessage();
}
}
}
//here is my method getFileName
function getFileName($employee_id)
{
//mysql query to fetch data
$sql = mysql_query("SELECT resume_path from employee_registration where
employee_id = '$employee_id'") or die(mysql_error());
while ($row = mysql_fetch_array($sql, MYSQL_ASSOC))
{
$response=$row['resume_path'];
}
$resume_name = explode("/", $response);
echo $resume_name[4];
return $resume_name;
}
Change below line:
move_uploaded_file($_FILES['pdf']['name'],$upload_path) ;
To
move_uploaded_file($_FILES['pdf']['tmp_name'],$upload_path) ;
tmp_name should be used to upload the file, as it has the full path of the file where it is temporarily stored. Where as the name contain only the name of file without any path information.
if this doenst work move_uploaded_file($_FILES['pdf']['tmp_name'],$upload_path) ;
kindly use this file_put_contents($upload_path,$_FILES['pdf']['tmp_name']);

how get parameter with POST method from rest client to php

i need to save in a folder on server pdfs and in a db the relative url.
but with the code that i show you below i get the error in php:"please choose a file"...i don't know why.
I show you my code:
REST CLIENT SIDE:
enter image description here
SERVER SIDE:
<?php
//importing dbDetails file
require_once 'dbDetails.php';
//this is our upload folder
$upload_path = 'uploads/';
//Getting the server ip
$server_ip = gethostbyname(gethostname());
//creating the upload url
//$upload_url = 'http://'.$server_ip.'/AndroidImageUpload/'.$upload_path;
$upload_url = 'http://'.$server_ip.'/azz/'.$upload_path;
//response array
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
//checking the required parameters from the request
if( isset($_POST['nome_pdf']) && isset($_FILES['pdf']['nome_pdf']) && isset($_POST['id'])){
//connecting to the database
$con = mysqli_connect(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_NAME) or die('Unable to Connect...');
//getting name from the request
$nome = $_POST['nome_pdf'];
//getting file info from the request
$fileinfo = pathinfo($_FILES['pdf']['nome_pdf']);
//getting the file extension
$extension = $fileinfo['extension'];
$id = $_POST['id'];
//file url to store in the database
$file_url = $upload_url . getFileName() . '.' . $extension;
//file path to upload in the server
$file_path = $upload_path . getFileName() . '.'. $extension;
//trying to save the file in the directory
try{
//saving the file
move_uploaded_file($_FILES['pdf']['tmp_name'],$file_path);
$sql = "INSERT INTO `my_db`.`pdfss` (`id_pdf`, `nome_pdf`, `url_pdf`,`id_user`) VALUES (NULL, '$nome','$file_url', '$id');";
//adding the path and name to database
if(mysqli_query($con,$sql)){
//filling response array with values
$response['error'] = false;
// $response['url'] = $file_url;
// $response['name'] = $name;
$response['nome_pdf'] = $nome;
$response['url_pdf'] = $file_url;
}
//if some error occurred
}catch(Exception $e){
$response['error']=true;
$response['message']=$e->getMessage();
}
//closing the connection
mysqli_close($con);
}else{
$response['error']=true;
$response['message']='Please choose a file';
}
//displaying the response
echo json_encode($response);
}
I hope that you can help me!
This line
if( isset($_POST['nome_pdf']) && isset($_FILES['pdf']['nome_pdf']) && isset($_POST['id'])){
Should be
if( isset($_POST['nome_pdf']) && isset($_FILES['nome_pdf']['tmp_name']) && isset($_POST['id'])){
Or
if( isset($_POST['nome_pdf']) && isset($_FILES['nome_pdf']['name']) && isset($_POST['id'])){
Your error comes from here
isset($_FILES['pdf']['nome_pdf'])
NOTE: You do not use $_POST when dealing with file uploads in PHP. Use $_FILES. I think you are confused with the name of the file and also the array_keys that are associated with the $_FILES array
nome_pdf is not in the $_FILES array. If you try a dump of var_dump($_FILES['pdf']);, you will see that nome_pdf is not in the array.
Replace the line with:
if( isset($_FILES['pdf']) && $_FILES['pdf']['tmp_name'] != '' && isset($_POST['id'])){
#add your code
else{
$response['error']=true;
$response['message']= 'PDF FILE: '. $_FILES['pdf'].' ID of post: '.$_POST['id'];
exit;
}
echo(json_encode($reponse));
The above change will make sure the tmp_name is not empty.
Also before moving the file, i suggest using mime type to check for the extensions

Android - Display all images from server folder using PHP in GridView

I am trying to capture image or record a video using camera and then upload to my server. On the server side, i used PHP language to read the file and moved it to a particular location. Now i want to display all these images that are stored my server. Please help me.
This is the upload image PHP script
<?php
// Path to move uploaded files
$target_path = "uploads/";
// array for final json respone
$response = array();
// getting server ip address
$server_ip = gethostbyname(gethostname());
// final file url that is being uploaded
$file_upload_url = 'http://' . $server_ip . '/' . 'AndroidFileUpload' . '/' . $target_path;
if (isset($_FILES['image']['name'])) {
$target_path = $target_path . basename($_FILES['image']['name']);
// reading other post parameters
$email = isset($_POST['email']) ? $_POST['email'] : '';
$website = isset($_POST['website']) ? $_POST['website'] : '';
$response['file_name'] = basename($_FILES['image']['name']);
$response['email'] = $email;
$response['website'] = $website;
try {
// Throws exception incase file is not being moved
if (!move_uploaded_file($_FILES['image']['tmp_name'], $target_path)) {
// make error flag true
$response['error'] = true;
$response['message'] = 'Could not move the file!';
}
// File successfully uploaded
$response['message'] = 'File uploaded successfully!';
$response['error'] = false;
$response['file_path'] = $file_upload_url . basename($_FILES['image']['name']);
} catch (Exception $e) {
// Exception occurred. Make error flag true
$response['error'] = true;
$response['message'] = $e->getMessage();
}
} else {
// File parameter is missing
$response['error'] = true;
$response['message'] = 'Not received any file!F';
}
// Echo final json response to client
echo json_encode($response);
?>
upload Camera image:
i want to display theses images synchronised when i upload images again.
Config.java
public class Config {
// File upload url (replace the ip with your server address)
public static final String FILE_UPLOAD_URL = "http://wangjian.site90.net/AndroidFileUpload/fileUpload.php";
// Directory name to store captured images and videos
public static final String IMAGE_DIRECTORY_NAME = "Android File Upload";
I'm a newbie at this stuff so any help will be appreciated. thanks so much! And i will upload more details if needed.
Have an API endpoint return the URLs of the images that you have uploaded and then call them from the app.
Like,
public static final String FILE_DOWNLOAD_URL = "http://wangjian.site90.net/AndroidFileUpload/getUserPhotos.php";
Let this return some JSON Array like,
{
"urls" : [
{
"url" : "url of pic 1"
},
{
"url" : "url of pic 2"
},
..
]
}
Have a custom GridAdpater with an ImageView in it. Use libraries like Picasso to load the images from the url into your GridView using the custom adapter with a custom view (Here, ImageView).
Call this API endpoint every time when the user is on the screen so that you'll be able to fetch the list of uploaded photos and show them everytime.

Categories