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?
Related
I need to download all photos about estates from an XML to save on the server. Every estate child in the XMl has a general section with all information and then a node called Foto (estate's photos) and another one for plans (Planimetria). The link of every image is structured as is:
<Link>http://www.site.it/ImageView.ashx?id=[photoID]&reduce=1438[can be set as I want es: 1000, 960, 1080]</Link>
I need to call it inside the $url_photo and $url_plan so I can read the photoID from XML and set resolution (1438,1000,960) with a global variable.
This is my code:
<?php
$xml = simplexml_load_file("Schede.xml"); // your xml
$path = '/mnt/c/Users/Giuseppe/Desktop/FotoTest/';
$i = 1;
$resolution = '1000';
// Estate Image
foreach($xml->CR03_SCHEDE as $estate){
//if((string) $estate['ELIMINATO'] = "NO"){
echo "\nEstate n $i Images\n";
foreach($estate->Foto->CR04_SCHEDE_FOTO as $photo){
$url_photo = (string) $photo->Link;
$filename_photo = basename($photo->CR04_FILENAME); // get the filename
if(file_exists($path . $filename_photo)) {
echo "file $filename_photo already exists \n";
}
else {
$img_photo = file_get_contents($url_photo); // get the image from the url
file_put_contents($path . $filename_photo, $img_photo); // create a file and feed the image
echo "file $filename_photo created \n";
}
}
// Plans
echo "\nEstate n $i plans\n";
foreach($estate->Planimetria->CR04_SCHEDE_FOTO as $plan) {
$url_plan = (string) $plan->'http: // www.site.it/ImageView.ashx?id=' . $plan->ID . '&reduce=' . $resolution; //$plan->Link;
$filename_plan = basename($plan->CR04_FILENAME);
if(file_exists($path . $filename_plan)) {
echo "file planimetry $filename_plan already exists \n";
}
else {
$img_plan = file_get_contents($url_plan); // get the image from the url
file_put_contents($path . $filename_plan, $img_plan); // create a file and feed the image
echo "file planimetry $filename_plan created \n";
}
}
$i++;
/*}
else{
echo "$estate->attributes(Riferimento)"."Deleted\n";
}*/
}
?>
I also have a problem with the first if commented:
if((string) $estate['ELIMINATO'] = "NO")...
Eliminato is an attribute of CR03_SCHEDE but the script won't read it and in any case go inside the if.
The complete XML has about 70/80 properties and the foreach works well to download all images, but I need that it should download the only one that has that attribute equals to NO
This is the example of XML (only one estate): link
Thanks to all
This is a classic mistake:
if((string) $estate['ELIMINATO'] = "NO")
You used the assignment operator instead of the comparison operator. Please use this exact form:
if ('NO' == (string)$estate['ELIMINATO'])
I have a piece of code to upload a picture and save it in a folder and the path in a databaseand show it on the webpage. Funny enough, upon uploading the picture for the first time, the image will show on the webpage and with change when I upload a new picture. But when I close the page, reopen it another day and decide to change the picture, the one of the webpage won't change even if i refresh the page but the one in the folder will change.
Here's my code
<?php
$sql2 = "SELECT Picture_HD FROM detailss WHERE Idn_nom = '$Indnum'";
require('connect.php');
$addr = "";
$addr = mysqli_query($conn, $sql2);
if ($addr) {
$locat = $addr->fetch_row();
$locat = (string)$locat[0];
} else {
$locat = "Pictures/default1.png";
}
mysqli_close($conn);
echo "<div id = 'Img'>";
echo "<img src = '" . $locat . "' alt = 'Passport picture/Headshot' style = 'width:80px; height:80px;'/>";
echo "</div>";
?>
Your browser is caching the image.
If you want to prevent the browser to cache the image just add a random parameter at the end of the url.
echo "<img src = '" . $locat . "?t=" . time() . "' alt = 'Passport picture/Headshot' style = 'width:80px; height:80px;'/>";
If your image is changing in your folder but you are seeing the old one on the webpage it's likely a caching issue, clear your browser cache (ctrl+f5 plus this is kinda broken so doesn't always work - so best to go into browser settings to do it, or open a private window after ctrl+f5) and if not the clear server level cache.
The best way to do this is to delete the existing image right before uploading the new one with the same file name
// define variables used for file name from session variable username the directory and extension by exploding the file name from the post method from a form with a metadata type
//set new file name to username from session variable
$filename = $_SESSION['username']
// set directory of files
$dir = "img/";
// set extension variable to file extension after posted from form
$ext=strtolower(end(explode('.',$_FILES['importimg']['name'])));
// new file upload name with existing extension
$upload_file = $dir . $filename . "." . $ext;
// delete file
// find all files with the same name any extension using variable defined above etc .txt, .php, .gif, .jpg, etc. then delete it
foreach (glob("img/$filename.*") as $deletefile) {
// unlink is used to delete the file and delete the cache of the file
unlink($deletefile);
}
// upload image
// upload file with type posted from metadata in form and upload it as your new file name using upload_file variable
if (move_uploaded_file($_FILES['importimg']['tmp_name'], $upload_file)) {
// successful upload of file add code for msg or sql query etc name to users table and redirect to profile page
echo "Successfully uploaded your file.";
} else {
// upload error show message
echo "There was an error uploading your file.";
}
Enjoy
I am trying to upload Excel file using PHP. I am using WAMP server and written PHP code to upload Excel file in the same folder.
I have saved an Excel file so if I upload the saved file then it works fine but if I try to upload another Excel file from different location i.e. from desktop it is showing that abc.xls is not readable.
My code is as follows:
<?php
ini_set("display_errors",1);
require_once 'excel_reader2.php';
require_once 'db.php';
if(isset($_POST["btnImport"]))
{
if(!empty($_FILES["excelFile"]["tmp_name"]))
{
$fileupload = $_FILES["excelFile"]["name"];
$fileName = explode(".",$_FILES["excelFile"]["name"]);
if($fileName[1]=="xls"||$fileName[1]=="xlsx")
{
$data = new Spreadsheet_Excel_Reader($fileupload);
//echo "Total Sheets in this xls file: ".count($data->sheets)."<br /><br />";
$html="<table border='1'>";
for($i=0;$i<count($data->sheets);$i++) // Loop to get all sheets in a file.
{
if(count(#$data->sheets[$i]['cells'])>0) // checking sheet not empty
{
// echo "Sheet $i:<br /><br />Total rows in sheet $i ".count($data->sheets[$i]['cells'])."<br />";
for($j=1;$j<=count($data->sheets[$i]['cells']);$j++) // loop used to get each row of the sheet
{
$html.="<tr>";
for($k=1;$k<=count($data->sheets[$i]['cells'][$j]);$k++) // This loop is created to get data in a table format.
{
$html.="<td>";
#$html.=$data->sheets[$i]['cells'][$j][$k];
$html.="</td>";
}
#$data->sheets[$i]['cells'][$j][1];
#$ques = mysql_real_escape_string($data->sheets[$i]['cells'][$j][1]);
$opt1 = mysql_real_escape_string($data->sheets[$i]['cells'][$j][2]);
$opt2 = mysql_real_escape_string($data->sheets[$i]['cells'][$j][3]);
$opt3 = mysql_real_escape_string($data->sheets[$i]['cells'][$j][4]);
#$opt4 = mysql_real_escape_string($data->sheets[$i]['cells'][$j][5]);
#$correct = mysql_real_escape_string($data->sheets[$i]['cells'][$j][6]);
#$Level = mysql_real_escape_string($data->sheets[$i]['cells'][$j][7]);
#$Category = mysql_real_escape_string($data->sheets[$i]['cells'][$j][8]);
#$explain = mysql_real_escape_string($data->sheets[$i]['cells'][$j][9]);
$nithi = "INSERT INTO `question` VALUES (NULL,'".$ques."','".$opt1."','".$opt2."','".$opt3."','".$opt4."','".$correct."','".$Level."','".$Category."','".$explain."')";
if (!mysql_query($nithi,$connection))
{
die('Error: ' . mysql_error());
}
$result = mysql_query("SET NAMES utf8");//the main trick
$cmd = "select * from TAMIL";
$result = mysql_query($cmd);
}
}
}}}}
if(#$result){
echo "Questions uploaded successfully";
}
?>
How can I upload Excel file from different location?
When a file is uploaded in PHP, it is put into temp folders.
In your code, there is no call for moving the uploaded file from temporary location into the desired one. Instead you are only checking $_FILES["excelFile"]["tmp_name"] and then directly using $_FILES["excelFile"]["name"] which is obviously incorrect.
Use move_uploaded_file() function to move the file, see the docs: http://php.net/move_uploaded_file
I want to upload 1000 images in just one click via URL. I have 1000 Image URLs stored in MYSQL database.
So please any one give me PHP code to upload that 1000 images via URL through mysql database.
Currently I am using the bellow code:-
It upload one image per click by posting URL of image...
But i want to upload 1000 image in one click by getting URLs from databse
$result = mysql_query("SELECT * FROM thumb") or die(mysql_error());
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
echo "<div>";
$oid = $row['tid'];
$th= $row['q'];
echo "</div>";
$thi = $th;
$get_url = $post["url"];
$url = trim('$get_url');
if($url){
$file = fopen($url,"rb");
$directory = "thumbnail/";
$valid_exts = array("php","jpeg","gif","png","doc","docx","jpg","html","asp","xml","JPEG","bmp");
$ext = end(explode(".",strtolower(basename($url))));
if(in_array($ext,$valid_exts)){
$filename = "$oid.$ext";
$newfile = fopen($directory . $filename, "wb");
if($newfile){
while(!feof($file)){
fwrite($newfile,fread($file,1024 * 8),1024 * 8);
}
echo 'File uploaded successfully';
echo '**$$**'.$filename;
}
else{
echo 'File does not exists';
}
}
else{
echo 'Invalid URL';
}
}
else{
echo 'Please enter the URL';
}
}
Thanks a lot.... …
The code you have is outdated and a lot more complex than needed. This is not a site where you get code because you ask, this is a learning environment.
I'll give you an example on which you can continue:
// Select the images (those we haven't done yet):
$sItems = mysql_query("SELECT id,url FROM thumb WHERE imported=0") or die(mysql_error());
// Loop through them:
while( $fItems = mysql_fetch_assoc($sItems) ){
$imgSource = file_get_contents($fItems['url']); // get the image
// Check if it didn't go wrong:
if( $imgSource!==false ){
// Which directory to put the file in:
$newLocation = $_SERVER['DOCUMENT_ROOT']."/Location/to/dir/";
// The name of the file:
$newFilename = basename($fItems['url'], $imgSource);
// Save on your server:
file_put_content($newLocation.$newFilename);
}
// Update the row in the DB. If something goes wrong, you don't have to do all of them again:
mysql_query("UPDATE thumb SET imported=1 WHERE id=".$fItems['id']." LIMIT 1") or die(mysql_error());
}
Relevant functions:
file_get_contents() - Get the content of the image
file_put_contents() - Place the content given in this function in a file specified
basename() - given an url, it gives you the filename only
Important:
You are using mysql_query. This is deprecated (should no longer be used), use PDO or mysqli instead
I suggest you make this work from the commandline and add an echo after the update so you can monitor progress
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.