Search code examples
javascriptnode.jsazureazure-storageazure-blob-storage

Save file to azure storage using streams not working


I would like to save a file into stream container from a stream using azure-storage package

Here's how I get stream

let request = rp(options).on("response", async (response) => {
  if (response.statusCode === 200) {
    await insertFile("TTSOutput.wav", request, request.length);
}

Here's how I save it into Azure

var insertFile = async function (blobName, stream) {
  try {
    blobService = await azure.createBlobService(connStr);

    blobService.createContainerIfNotExists(
      containerName,
      {
        publicAccessLevel: "blob",
      },
      (err, result, response) => {
        if (!err) {
          let resultstream = blobService.createWriteStreamToBlockBlob(
            containerName,
            blobName
          );
          stream.pipe(resultstream);
        }
      }
  );
}

Actually only container is created but no file is get uploaded


Solution

  • Try the code below to upload a .wav file from Azure TTS API:

    let request = rp(options)
            .on('response', (response) => {
                if (response.statusCode === 200) {
                    tempFilePath = 'd:/temp.wav'
                    request.pipe(fs.createWriteStream(tempFilePath));
                    insertFile('TTSOutput.wav',fs.createReadStream(tempFilePath)).then(function(){
                        fs.unlinkSync(tempFilePath)
                        console.log("uploaded")})
                }
            });
    

    insertFile function:

    const {
        BlobServiceClient
      } = require('@azure/storage-blob');
    
    var conn_str = '<storage account connection string>'
    var container = '<your container name>'
    
    async function insertFile(blobName, stream) {
       
        BlobServiceClient.fromConnectionString(conn_str).getContainerClient(container).getBlockBlobClient(blobName).uploadStream(stream)
    
    }
    

    Result:

    enter image description here enter image description here

    Let me know if you have any more questions.