I have written this code to fetch data and I am getting response like this
async function streamToString(readableStream) {
return new Promise((resolve, reject) => {
const chunks = [];
readableStream.on("data", (data) => {
chunks.push(data.toString());
});
readableStream.on("end", () => {
resolve(chunks.join(""));
});
readableStream.on("error", reject);
});
}
if (type == "download") {
const name = req.query.name || req.body.name;
const itemname = req.query.itemname || req.body.itemname;
var container = name ? name : "securesharecc";
const containerClient = await blobServiceClient.getContainerClient(container);
const blobName = itemname ? itemname : "sample.png";
const blockBlobClient = containerClient.getBlockBlobClient(blobName);
const downloadBlockBlobResponse = await blockBlobClient.download(0);
console.log("\nDownloaded blob content...");
var base64string = await streamToString(downloadBlockBlobResponse.readableStreamBody);
console.log("\t", base64string);
context.res = {
body: { data: base64string }
};
context.done();
}
so this code shows a string of a file using the item name in a container from azure.
But I'm getting responses like this
{
"data": "PNG\r\n\u001a\n\u0000\u0000\u0000\rIHDR\u0000\u0000\u0002�\u0000\u0000\u0001�\b\u0002\u0000\u0000\u0000\u000f�\u001fl\u0000\u0000\u0000\u0001sRGB\u0000��\u001c�\u0000\u0000\u0000\u0004gAMA\u0000\u0000��\u000b ....."
}
What to code if I want to directly download this file instead of showing contents, how to do this?
CodePudding user response:
Please try by changing your streamToString
method to something like:
async function streamToString(readableStream) {
return new Promise((resolve, reject) => {
let chunks = Buffer.from([]);
readableStream.on("data", (data) => {
chunks = Buffer.concat([chunks, data], chunks.length data.length);
});
readableStream.on("end", () => {
resolve(chunks);
});
readableStream.on("error", reject);
});
}
Essentially image files are binary files and you should not try to convert its data into string.