Upload and Download images in Azure Blob Storage - php

I am trying to upload an image from a HTML form to Azure Blob Storage using the Azure PHP SDK. The problem appears when I try to download the image. The result page can be seen at the bottom of the post.
I store the image using the temporary name and I think this is one of the two problems. I am not sure but the second problem is to when downloading the image. Do I have to convert it from the getContentStream() to image ?
$_FILES['driverLicenseFront']['tmp_name']
This is the html form to upload the image:
<form role="form" method="POST" action="{path_to_controller}" data-toggle="validator" enctype="multipart/form-data">
<div class="form-group">
<label for="driverLicenseFront">Upload Driver's License(Front)</label>
<input type="file" id="driverLicenseFront" name="driverLicenseFront">
</div>
<submit button>
</form>
In the controller I store the file like this:
// First check if there is a container
$blob = New Blob($_SESSION['userid']);
$blob->createContainerIfNotExists();
// Upload image to Azure Blob Storage
$content = fopen($_FILES['driverLicenseFront']['tmp_name'].'', "r");
$blob->uploadToContainer($content,'DriverLicenseFrontSide');
Blob is my custom class to handle blobs
I need to download the file using a link:
Download
I catch the request in the controller:
if(isset($_GET['blob_name'])){
$blob = New Blob($_SESSION['userid']);
$blob->downloadBlob($_GET['blob_name']);
}
The function of the Blob class:
public function downloadBlob($blob_name){
try {
// Get blob.
$blob = $this->blobRestProxy->getBlob($this->containerName, $blob_name.'.jpg');
fpassthru($blob->getContentStream());
}
catch(ServiceException $e){
// Handle exception based on error codes and messages.
// Error codes and messages are here:
// http://msdn.microsoft.com/library/azure/dd179439.aspx
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}
}
The result:
����JFIF,,���ICC_PROFILE�mntrRGB XYZ
�$acsp���-)�=ޯ�U�xB��ʃ9 descDybXYZ�bTRC�dmdd ��gXYZ
hgTRC�lumi |meas �$bkpt �rXYZ �rTRC�tech �vued
��wtptpcprt�7chad�,descsRGB IEC61966-2-1 black scaledXYZ
$����curv #(-27;#EJOTY^chmrw|�������������������������...

It seems that you forget to add the content-type of response to convert the binary content to image content.
Try to add the following code in your downloadBlob() function.
$blob = $this->blobRestProxy->getBlob($this->containerName, $blob_name.'.jpg');
header("Content-Type:image/jpeg");
header('Content-Disposition: attachment; filename="' . $blob_name . '"');
fpassthru($blob->getContentStream());
Any further concern, please feel free to let me know.

Related

how to convert page to pdf in php

I have an html page like JsFiddle and I want convert this in pdf, i can't create the line to line pdf because the page is dinamically create, I use php for calling a fiel that connect to mysql and fill a template file like.
$_POST['IdQuestionario']=5;
$_POST['IdUtente']=10001;
$_POST['Visualizza']=true;
$_POST['IdImpianto']=1;
$_POST['Stampa']=true;
$_POST['TipoImpianto']='grande';
ob_start();
ob_clean();
require_once 'intro.php';
$tbl=ob_get_clean();
$html.=$tbl;
I'm trying with tcpf, mpdf , jsPDF but i cant obtain a discrete output because I use colgroup for table. anyone say me a method for render the page,if is possible whitout install software on server.
There a few that i know of - some have problems with tables, I would avoid DOMPDF - known issues with tables.
There's one that's recommended from cvision; i don't have a code sample, but you can download it free and even sample it online.
There's also a php-pdf product available from muhimbi (a little lesser-known!, but i think it's free)
<?php
// Include the generated proxy classes
require_once "documentConverterServices.php";
// Check the uploaded file
if ($_FILES["file"]["error"] > 0)
{
echo "Error uploading file: " . $_FILES["file"]["error"];
}
else
{
// Get the uploaded file content
$sourceFile = file_get_contents($_FILES["file"]["tmp_name"]);
// Create OpenOptions
$openOptions = new OpenOptions();
// set file name and extension
$openOptions->FileExtension = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);
$openOptions->OriginalFileName = $_FILES["file"]["name"];
// Create conversionSettings
$conversionSettings = new ConversionSettings();
// Set the output format
if(isset($_POST["outputFormat"]))
{
$conversionSettings->Format = $_POST["outputFormat"];
} else {
$conversionSettings->Format = "PDF";
}
// Set fidelity
$conversionSettings->Fidelity = "Full";
// These values must be set to empty strings or actual passwords when converting to non PDF formats
$conversionSettings->OpenPassword="";
$conversionSettings->OwnerPassword="";
// Set some of the other conversion settings. Completely optional and just an example
$conversionSettings->StartPage = 0;
$conversionSettings->EndPage = 0;
$conversionSettings->Range = "VisibleDocuments";
$conversionSettings->Quality = "OptimizeForPrint";
$conversionSettings->PDFProfile = "PDF_1_5";
$conversionSettings->GenerateBookmarks = "Automatic";
$conversionSettings->PageOrientation="Default";
// Create the Convert parameter that is send to the server
$convert = new Convert($sourceFile, $openOptions, $conversionSettings);
// Create the service client and point it to the correct Conversion Service
$url = "http://localhost:41734/Muhimbi.DocumentConverter.WebService/?wsdl";
$serviceClient = new DocumentConverterService(array(), $url);
// If you are expecting long running operations then consider longer timeouts
ini_set('default_socket_timeout', 60);
try
{
// Execute the web service call
$result = $serviceClient->Convert($convert)->ConvertResult;
// Send the resulting file to the client.
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"convert." . $conversionSettings->Format . "\"");
echo $result;
}
catch (Exception $e)
{
print "Error converting document: ".$e->getMessage();
}
}
?>
Also, you could investigate 'Snappy' (has dependencies)
You can try WKHTMLTOPDF.
Here is a Stackoverflow Thread on how to use it with PHP.
How do I get WKHTMLTOPDF to execute via PHP?
And here is a wrapper for PHP
https://github.com/mikehaertl/phpwkhtmltopdf
MPDF one of best library to convert pdf, try it
MPDF link : http://www.mpdf1.com/mpdf/index.php
Example link : http://mpdf1.com/common/mpdf/examples/

Yii2: Error Not allowed to load local resource

Im trying to display images from backend of my app
<?php foreach ($img as $key=>$row): ?>
<div class="products_inside_wrapper intro_wrapper">
<div class="classes_inside_item bordered_wht_border">
<?php
foreach (explode(';',rtrim($row['images'],';')) as $key_img => $value_img)
{
?>
<?php echo Html::img('#backend/web'.'/'.$value_img);?>
<?php
}
?>
</div>
</div>
<?php endforeach; ?>
Tried with above code to display all images, but getting error Not allowed to load local resource when I open Google Chrome Inspect Element
i think you are using a local url instead of using this
<?php echo Html::img('#backend/web'.'/'.$value_img);?>
try using it like
<?= Html::img(Yii::getAlias('#web').'/images/'.$value_img]);?>
As stig-js answered you can't load local saved image directly, If you're really interested into loading resources from a local path, you can open image as a binary file with fopen and echo the content of it with a proper header to output. In general way, you can add a method to your model like this:
public function getImage($imageName)
{
$imagePath = '#backend/web' . '/' . $imageName;
$fileInfo = finfo_open(FILEINFO_MIME_TYPE);
$contentType = finfo_file($fileInfo, $imagePath);
finfo_close($fileInfo);
$fp = fopen($imagePath, 'r');
header("Content-Type: " . $contentType);
header("Content-Length: " . filesize($imagePath));
ob_end_clean();
fpassthru($fp);
}
P.S: Also you can use combination of this answer with showing image as base64 on HTML. See How to display Base64 images in HTML?
Images must be accesible by an url, like
yoursite.com/backend/imagedir/IMG'
If yoursite.com/backend points to your backend/web folder.
Backend alias points to your local path, so you need a custom alias to reach image folders.
Yii2 aliases: http://www.yiiframework.com/doc-2.0/guide-concept-aliases.html

azure image blob is prompting download option

okay i someone find out how to upload blobs in container of using php on azure, but when even i view the image with plain url like https://my.blob.url.net/my_image_folder/my_image_name.jpg the browser prompts to download the image, instead of viewing the image, like normal image is viewed on browser, here is the code i'm using while uploading
<?php
require_once __DIR__.'/vendor/autoload.php';
use WindowsAzure\Common\ServicesBuilder;
$connectionString = 'DefaultEndpointsProtocol=http;AccountName=account_name;AccountKey=my_key_value';
$blobRestProxy = ServicesBuilder::getInstance()->createBlobService($connectionString);
$content = fopen('folder/image.jpg','r');
$blob_name = 'image_name.jpg';
try
{
$blobRestProxy->createBlockBlob("container_name", $blob_name, $content);
}
catch(ServiceException $e)
{
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}
this code is working fine, but when accessing the url, it prompts download option, which means i cannot use for img html tag
You have to set the blob's content type to an appropriate mime type. The following is a snippet in C# that shows how this can be done:
entryData.DestinationBlob.Properties.ContentType = "image/jpeg";
entryData.DestinationBlob.SetProperties();
We need to set its property Content type through Blob Options class.
PHP :
namespace - use MicrosoftAzure\Storage\Blob\Models\CreateBlobOptions;
//use code where you are creating blob
$opts = new CreateBlobOptions();
//$opts->setCacheControl('test');
$opts->setContentEncoding('UTF-8');
$opts->setContentLanguage('en-us');
//$opts->setContentLength(512);
$opts->setContentMD5(null);
$opts->setContentType($mimeType);
$blobRestProxy->createBlockBlob($containerName, $indexFile, $content,$opts);
$mimeType is Type of your file text/html, text/pdf. It will work in git.
package : "microsoft/windowsazure": "^0.5"

How to recieve an image (file) with PHP that was submitted over a POST request

I have a file: success.jpg
I would like to send this file over an HTTP POST request and have it land in a public directory on my server.
I have a simple HTML form and PHP processor that work if I'm uploading from the browser: php.net/manual/en/features.file-upload.post-method.php
I'm trying to drop the use of a form altogether and just pass data over POST to a URL (e.g. myimageserver.com/public/upload.php).
It seems that I can use the PHP function move_uploaded_file and it even talks about using POST here: http://php.net/manual/en/function.move-uploaded-file.php but it doesn't provide the code which can receive and store a file that has been uploaded with POST.
Has anyone ever done something similar?
If you want to upload using a mobile app for example, you have to send via POST the base64 content of the image with the mimetype or the file extension of it, and then use something like this:
Send the content base64 encoded and urlescaped.
Receive the content and do base64 decode and then urldecode.
Then in PHP just do:
<?php
$base64decodedString = base64_decode(urldecode($_POST['yourInputString']));
$fileName = $_POST['fileNameString'];
file_put_contents($fileName, $base64decodedString);
This will generate a file with the content
You couold read this example http://www.w3schools.com/php/php_file_upload.asp
which basically does something like this:
<?php
$target_dir = "uploads/";
$target_dir = $target_dir . basename( $_FILES["uploadFile"]["name"]);
$uploadOk=1;
if (move_uploaded_file($_FILES["uploadFile"]["tmp_name"], $target_dir)) {
echo "The file ". basename( $_FILES["uploadFile"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
The key is on the $_FILES global array.
To check if there were an error before appliying that example, you could use this example:
if ($_FILES['file']['uploadFile'] === UPLOAD_ERR_OK) {
/**
* Do the upload process mentioned above
**/
} else {
/**
* There were an error
**/
}
This is the basic HTML form to upload files
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="myFile" />
<input type="submit" value="Send" />
</form>
How to upload your file?
<?php
$uploaddir = '/www/uploads/'; //physical address of uploads directory
$uploadfile = $uploaddir . basename($_FILES['myFile']['name']);
if(move_uploaded_file($_FILES['myFile']['tmp_name'], $uploadfile)){
echo "File was successfully uploaded.\n";
/* Your file is uploaded into your server and you can do what ever you want with */
}else{
echo "Possible file upload attack!\n";
}
?>
Some details
- How to get the physical address of uploads directory?
Just create an index file into your upload dir and run this code
<?php echo getcwd();?>
It's done, if you need more details, just feel free to ask.
AGAIN THIS IS THE BASIC WAY.

How to use $_FILES to store a BLOB Windows Azure

I am using windows azure blob storage service to store data. My php file is this
<?php
require_once __DIR__ . '/vendor/autoload.php';
use WindowsAzure\Common\ServicesBuilder;
use WindowsAzure\Blob\Models\CreateContainerOptions;
use WindowsAzure\Blob\Models\PublicAccessType;
use WindowsAzure\Common\ServiceException;
// Create blob REST proxy.
$connectionString = "[CONNECTION STRING (WORKS)]";
$blobRestProxy = ServicesBuilder::getInstance()->createBlobService($connectionString);
$blob_name = "myblob";
// Create blob REST proxy.
try {
//Upload blob
$blobRestProxy->createBlockBlob("containerName",$blob_name, $_FILES['userfile']['tmp_name']);
echo '104';
}
catch(ServiceException $e){
// Handle exception based on error codes and messages.
// Error codes and messages are here:
// http://msdn.microsoft.com/en-us/library/windowsazure/dd179439.aspx
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}
?>
The BLOB is created perfectly...
The only problem i'm having is when I use $_FILES['userfile']['tmp_name'] it actually stores in the BLOB the PATH of the file, not the contents of the file itself.
My question is, how can I store a BLOB using the $_FILES contents?
You need to read the contents of the file using file_get_contents() or other method:
$blob_content = file_get_contents($_FILES['userfile']['tmp_name']);
$blobRestProxy->createBlockBlob("containerName", $blob_name, $blob_content);
MS actually attempts to give an example here, however fopen() doesn't work like that.

Categories