azure image blob is prompting download option - php

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"

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/

Upload and Download images in Azure Blob Storage

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.

replacing the process with file url instead of file upload in php

am uploading a Pdf file and passing it to getExtact function to extract pages from file which is being uploaded if any error in extraction we will send the file to decryptPDF function for which the input parameters are filename and filetempname for both the functions but here am using a file upload process i want to use file url like www.domainname.com/docs/1.pdf so that all the functions which are written already can be used : Below is my code
//here for the above variable values are coming from uploaded file here i want to use file url and all the pdf are in my own server
$FileName = $_FILES['inputfile']['name'];
$TempFileName = $_FILES['inputfile']['tmp_name']; $Folderpath='/home/domain/public_html/pdftest/temp';
try {
.
GetExtract($TempFileName,$FileName);
} catch (Exception $e) {
$responce = DecryptPDF($Folderpath,$Filename,$TempFileName);
if($responce == ''){
$Inputfile = $Folderpath.'/un_'.$Filename;
GetExtract($Inputfile,$FileName);
}else{
echo $responce;
}
As per my knowledge,local server $PATH is "/var/www/".Try putting your inputfiles in that location.Then only you can access the files using url.

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.

azure: Set blob content type using PHP

How do I use the setBlobProperties in php to set the ContentType? The code below is what I found via google, but that one isn't working. The video does appear in the blob storage, but the content-type is set to: application/octet-stream. Also the language isn't set to 'nl-BE' but shows 'empty'.
$storageClient->putLargeBlob($_POST['container'], $_POST['filename'], $tempFile);
$storageClient->setBlobProperties($_POST['container'], $_POST['filename'], null, array(
'x-ms-blob-content-language' => 'nl-BE',
'x-ms-blob-content-type' => 'video/mp4'
));
Ok, excuse me.. this code does work, but I was referring to the wrong one (had two php pages with the same name, and was editing in the one that i'm not using).
Sorry! But now, someone who is looking for this in the future, will have this as the answer :).
Using new sdk, one can set the content type as follows(i have set the content type for gif image in this example).
$blobRestProxy = ServicesBuilder::getInstance()->createBlobService($connectionString);
//upload
$blob_name = "image.gif";
$content = fopen("image.gif", "r");
$options = new CreateBlobOptions();
$options->setBlobContentType("image/gif");
try {
//Upload blob
$blobRestProxy->createBlockBlob("containername", $blob_name, $content, $options);
echo "success";
} catch(ServiceException $e){
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}

Categories