'How to Display pdf file from Azure Blob storage thru an Azure Function HTTPTrigger
Goal: I would like to display a pdf which was uploaded to my blobstorage into my UI(react)(a simple iframe can suffice). I cannot use SAS and the blobstorage would be private so my means of retrieving is only thru an Azure Function APP which i would supply the storage credentials to be able to get my pdf.
So far,I have a HttpTrigger Function App and i was able to get the pdf file from blobstorage to function App and i can see that the content length is correct and i am returning this thru the HttpResponse as bytes with mimetype="application/pdf". Please note as well that on my upload, i am setting already the content-type to "application/pdf" and this is reflecting on the blobstorage.
But on my UI, i could not load the file. I also tried to open the file thru a new window just to check if it will load but it was just saying "File could not load". File size as well is not matching and the size on UI very small as if there is no content that was read.
Below is my Function App code:
def main(req: func.HttpRequest) -> func.HttpResponse:
req_body = req.get_json()
blob = BlobClient.from_connection_string(conn_str=CONNECTION_STRING, container_name=CONTAINER, blob_name=req_body.get('filename'))
if blob.exists():
data = blob.download_blob()
data_content = data.readall()
logging.info("Content Length is " + str(data_content.__len__()))
return func.HttpResponse(data_content,mimetype="application/pdf",
status_code=200)
Below is my Request Code:
async function getFile() {
var data = {"filename":"sample pdf upload 1.pdf"}
fetch('http://localhost:7071/api/HttpTriggerDisplayFile',
{
method: 'POST',
headers: { 'Access-Control-Allow-Origin': '*', },
body: JSON.stringify(data),
}
).then((response) => {
//const file = new Blob([response.body],{type: 'application/pdf'});
const file = new Blob([response.blob()],{type: 'application/pdf'});
console.log(response);
const fileURL = URL.createObjectURL(file);
//console.log(filesource);
//setfilesource(fileURL);
window.open(fileURL);
});
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
