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

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.

Related

Upload Image using Retrofit and PHP API

I am trying to upload image with Retrofit API. My android code is like below
public interface FileUploadService {
#Multipart
#POST("upload.php")
Single<ResponseBody> onFileUpload(#Part("username") RequestBody mUserName, #Part MultipartBody.Part file);
}
and PHP code is like below
<?php
$target_dir = "upload/";
$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 am not getting any error in android side and its working fine but in server, I am getting error like below
PHP Notice: Undefined index: file in line 3
Let me know what I am missing. Thanks!
In your server part code, you're expecting the field name to be file. I guess that while preparing multipart data in Android, you're not using the same name (file).
In your Activity/Fragment, the multipart data preparation code should look like below.
String fileName = "your file name with extension";
RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part.createFormData("file", fileName, requestBody);
// ----^^^^--- look at the field name (first parameter)

Cannot upload image using filepath in MS-Azure Blob Storage

I am developing a web application using Microsoft Azure services. I am following this link to upload an image to my blob storage, but there are a few bits and pieces missing in the document that leads to certain issues. For instance, how do we define the variable $fileToUpload and how will it relate to the variable $myfile? Also, if we want to choose to upload a file from our system when the application is running, in which of the two variables should we have the absolute file path to my image? The code I have written till now to upload an image is as follows:
function imageupload(string $current_user){
$pt_id = $_POST['patientid'];
if (strcmp($pt_id,"")==0){
echo "Select PatientID to continue";
}else{
$accountexists = load($current_user, $pt_id);
if ($accountexists == 0){
$error = "Patient Id does not exist";
echo $error;
}else{
$img_path = $_POST['uploadI'];
if (strcmp($img_path, "")==0){
echo "Enter valid image path <br />";
}
else{
require_once 'vendor/autoload.php';
$connectionString = '****';
// Create blob client.
$blobClient = BlobRestProxy::createBlobService($connectionString);
# Create the BlobService that represents the Blob service for the storage account
$containerName = $current_user;
$num = rand(10,10000);
$num2 = (string) $num;
$fileToUpload = $pt_id."_".$num2;
# Upload file as a block blob
echo "Uploading image: ".PHP_EOL;
echo $img_path;
echo "<br />";
$content = fopen($img_path, "r");
//Upload blob
$blobClient->createBlockBlob($containerName, $fileToUpload, $content);
echo "Image uploaded successfully! <br />";
}
}
}
}
In this code, I am storing my path to the image in the variable $img_path. And this is the code I am using for displaying the image later:
// Gets all the images from the hospital's container and filters out the images corresponding to a particular patient.
// For the patient, the image would be saved on cloud with name as: <patientid>_<some random number>
// Eg- patient id= pt1 , so image name could be- pt1_3682
function uploadedimage(string $current_user, string $HospitalId, string $PatientId){
$containerName = $HospitalId;
$url = "";
try{
// Get blob.
require_once 'vendor/autoload.php';
// use MicrosoftAzure\Storage\Common\ServicesBuilder;
$connectionString = '****';
$blobClient = BlobRestProxy::createBlobService($connectionString);
$blob_list = $blobClient->listBlobs($containerName);
$blobs = $blob_list->getBlobs();
$strlen = strlen($PatientId);
$array_user = array();
// echo "These are the blobs present in the container: ";
foreach($blobs as $blob)
{
$name = $blob->getName();
$namesub = substr($name,0, $strlen);
if (strcmp($namesub, $PatientId) == 0){
array_push($array_user, $blob);
}
}
}
catch(ServiceException $e){
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}
$url = "";
try {
foreach($array_user as $blob)
{
$name = $blob->getName();
$url = $blob->getUrl();
echo "<img src=\"".$url."\" alt=\"image post\"></br></br>";
}
}
catch(ServiceException $e){
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}
}
But I cannot seem to view my image in the html that I have specified. All I get is the default text "image post". Thus I have concluded there is something I am missing in my code due to which the images are not being uploaded but I can't seem to figure that out from the azure tutorial.
Edit: I checked my blob properties and they are all of 0 size, which means that they are not being uploaded properly. Also I realised that there are some images that were pushed to the cloud along with my code in my git folder. So if there is a particular image by the name abc.png already existing in the same directory as my code on Azure and while uploading this image from my web application, if in the path text box I specify only abc.png, that image gets uploaded in my container in it's correct size, but if that same image is present on my desktop and if I specify the complete filepath of my local system for this image (or some other image not present in the git directory existing on azure) as C:/Desktop/abc.png, it gets uploaded as only 0 bytes image (which is essentially not being uploaded properly). What can be the issues if it is not able to take images from my system and can only take the images already existing in it's git directory?

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

Email attachments from outside sources not working

I've recently created a page on our site where users can upload an image and email it to an email address set up specifically to keep the uploaded documents.
I've tested this myself and it works, with the attachments arriving in gmail as expected.
However, whenever someone from outside uses this feature the attachment in the email is unavailable, or not could not be loaded, when we try to open it.
The code is split between 2 files, a controller and a helper. Here's the code (For the sake of saving some space I've removed all error checks, but in the actual code they are all still in place and not picking up any errors whatsoever):
controller
$helper = [GET HELPER];
/** Upload the file to a temp location so that we can attach it to an email */
$uploader = new Varien_File_Uploader('filename');
$uploader->setAllowedExtensions(array(
'image/jpeg',
'image/jpg',
'image/png',
'application/pdf'
))
->setAllowRenameFiles(true)
->setFilesDispersion(false);
$path = $helper->getFileStorageLocation(); // Will store files in /tmp
if (!is_dir($path))
{
mkdir($path, 0775, true);
}
$uploader->save($path, $_FILES['filename']['name']);
$result = $helper->sendMail($_FILES['filename']['name']);
if ($result)
{
$uploadSuccess = true;
/** Remove the temp file */
unlink($path . DS . $_FILES['filename']['name']);
}
helper
/** Declare variables */
$order = Mage::getModel('sales/order')->load($orderId);
$file_incremented_id = $order->getIncrementId();
$copyTo = $this->getCopyTo();
$copyFrom = $this->getCopyFrom();
$subject = 'proof of upload for ' . $file_incremented_id;
$copyTo = explode(',', $copyTo);
$body = '<span>Please see attachment</span>';
$file = $this->getFileStorageLocation() . DS . $filename; // function receives filename from whatever is calling it
$attachment = file_get_contents($file);
$extension = pathinfo($file, PATHINFO_EXTENSION);
if (!$copyTo)
{
return false;
}
$mail = Mage::getModel('core/email_template');
$mail->setSenderName('Uploader');
$mail->setSenderEmail($copyFrom);
$mail->setTemplateSubject($subject);
$mail->setTemplateText($body);
$mail->getMail()->createAttachment(
$attachement,
Zend_Mime::TYPE_OCTETSTREAM,
Zend_Mime::DISPOSITION_ATTACHMENT,
Zend_Mime::ENCODING_BASE64,
$file_incremented_id . '.' . $extension // Set order number as file name
);
try
{
$mail->send($copyTo);
return true;
}
catch (Exception $e)
{
return false;
}
Can anyone see anything that might be causing the issue, or think of what it might be based on my explanation of the setup?
So the problem, in the end, was filesize. My fault for not posting the $_FILES variable.
I saw it a bit later and the variable had error = 1, meaning that the file's size was larger than what was allowed by the max_upload_filesize in the php.ini

Image Uploading from android application to Server is not working

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

Categories