1
votes

I want to download and save an Azure Storage blob as a file on my local computer using the file name from the Azure Storage. I'm using the steps from here ( tutorial link ) in a file I've called download.php, and I can see the file contents in my browser when I go to download.php. If I then put a link in index.php to download.php, I can right click the link and "save as", and save the file as myfile.doc. I can then open myfile.doc succesfully.

index.php:

echo '<a href="http://myserver/dev/download.php" >Click me</a>';

However... What I'd like to know is how to get the link to "save as" without the user having to right click. Also, I have the file name (from Azure Storage) -- but I don't know how to get the file to save using that file name. How do I get the file to save to the user's Downloads directory with the file name when the user clicks on the link?

1

1 Answers

1
votes

To do this, I change index.php to a form:

echo '<form method="post" action="download.php"><div id="divexport">';
   echo '<input type="hidden" name="Export" value="coverLetter">';
   echo '<input type="submit" id="Export" value="Cover Letter" />';
   echo '</div></form>';

And then added header info to download.php, just before fpassthru

// Create blob REST proxy.
$blobRestProxy = ServicesBuilder::getInstance()->createBlobService($connectionString);
$blobfile = "myblob.pdf";
$filename = basename($blobfile);
$ext = new SplFileInfo($filename);
$fileext = strtolower($ext->getExtension());

try {
    // Get blob.
    $blob = $blobRestProxy->getBlob("document", $blobfile);

    if($fileext === "pdf") {
        header('Content-type: application/pdf');
    } else if ($fileext === "doc") {
        header('Content-type: application/msword'); 
    } else if ($fileext === "docx") {
        header('Content-type: application/vnd.openxmlformats-officedocument.wordprocessingml.document'); 
    } else if($fileext === "txt") {
        header('Content-type: plain/text');
    }
    header("Content-Disposition: attachment; filename=\"" . $filename . "\"");
    fpassthru($blob->getContentStream());
}
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 />";
}