将 Cache-Control 和过期 headers 添加到 Azure Blob 存储节点 JS

Add Cache-Control and Expires headers to Azure Blob Storage Node JS

我正在使用 Azure 存储来提供静态文件 blob,但我想在提供时向 files/blobs 添加 Cache-Control 和 Expires header 以减少带宽成本。

但是我用的是Node JS

我该怎么做?

这是我到目前为止的情况:

更简单的解决方案:jsfiddle.net/fbqsfap2

//https://myaccount.blob.core.windows.net/mycontainer/myblob?comp=properties

function updateBlob(blobName, containerName, accountName, properties) {
    let xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
           console.log(xmlhttp.status);
           if (xmlhttp.status == 200) {
              const updatedPropertiesStr = getPropertiesKeysStr(properties);
              console.log("Update sucessfully ", updatedPropertiesStr);
           }
           else if (xmlhttp.status == 400) {
              console.log('There was an error 400');
           }
           else {
               console.log('Something else other than 200 was returned' , xmlhttp.status);
           }
        }
    };
    const url = "https://<account>.blob.core.windows.net/<container>/<blob>?cache-control='max-age=3600'";

    xmlhttp.open("PUT", url, true);
    xmlhttp.send();
}

function updateBlobPorperty(blobName, containerName, accountName, properties) {
    let xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
           console.log(xmlhttp.status);
           if (xmlhttp.status == 200) {
              const updatedPropertiesStr = getPropertiesKeysStr(properties);
              console.log("Update sucessfully ", updatedPropertiesStr);
           }
           else if (xmlhttp.status == 400) {
              console.log('There was an error 400');
           }
           else {
               console.log('Something else other than 200 was returned' , xmlhttp.status);
           }
        }
    };

    const getParameters = object2getParameters(properties);
    const url = `https://${accountName}/${containerName}/${blobName}?${getParameters}`;

    xmlhttp.open("PUT", url, true);
    xmlhttp.send();
}


function getPropertiesKeysStr(properties){
  return Object.keys(properties).reduce((actual, next) => actual.concat(` ${next}`), "");
}

function object2getParameters(object){

  let propertiesStr = "";
  for (key of Object.keys(object)) {
      let prop = `${key}=${object[key]}&`;
      propertiesStr += prop;
  }

  propertiesStr = propertiesStr.substr(0, propertiesStr.length-1);

  return propertiesStr;
}

使用 Node JS 的完整解决方案:jsfiddle.net/rhske0nj

const azure = require('azure-storage');
const got = require('got');
const Promise = require('promise');

// =============================== Consts Definitions ====================================
    const AZURE_STORAGE = 
    {
        ACCOUNT: "ACCOUNT",
        ACCESS_KEY: "ACCESS_KEY"
    }


    const blobService = azure.createBlobService(AZURE_STORAGE.ACCOUNT, AZURE_STORAGE.ACCESS_KEY);
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++




// =============================== API to Azure Functions ================================
    function getBlobsName(blobService, containerName){
        return new Promise(function(resolve, reject){
                blobService.listBlobsSegmented(containerName, null, function(err, result) {
                    if (err) {
                        reject(new Error(err));
                    } else {
                        resolve(result.entries.map(BlobResult => BlobResult.name))
                    }
                })
            });
    }

    function getContainersName(blobService){
        return new Promise(function(resolve, reject){
            blobService.listContainersSegmented(null, function(err, result) {
                if (err) {
                    reject(new Error(err));
                } else {
                    resolve(result.entries.map(ContainerResult => ContainerResult.name));
                }
            })
        });
    }
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


// =================================== Main Function =====================================
function update(blobService){
    getContainersName(blobService)
        .then(containersName =>
            containersName.forEach(cn => 
                getBlobsName(blobService, cn)
                    .then(BlobsName =>
                        BlobsName.forEach(bn => 
                            updateBlobPorperty(bn, cn, AZURE_STORAGE.ACCOUNT,
                                {
                                    headers: {
                                                "Cache-Control": "max-age=2592000"
                                              }
                                }
                                                )
                                .then(console.log("Sucessfully updated"))
                                .catch(console.log)
                                //.cacth(console.log("Something failed"))
                        )
                        //console.log
                    )
                    .catch(err => console.log(err))
                )
        )
        .catch(err => console.log(err))
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    update(blobService);


// =============================== Update Blob Block =====================================
    /*
        Example of Url:
        https://homologsquidmedia.blob.core.windows.net/squid-pic/1.jpg?cache-control=max-age=3600
    */
    function updateBlobPorperty(blobName, containerName, accountName, properties){

        const cdnFileUrl = `https://${accountName}.azureedge.net/${containerName}/${blobName}`;
        const fileUrl = `https://${accountName}.blob.core.windows.net/${containerName}/${blobName}`;

        console.log(`fileUrl:> ${fileUrl}`);

        //return got.put(fileUrl, properties);
        return got.put(fileUrl, properties);
        //return got.put(fileUrl);
    }

    function getPropertiesKeysStr(properties){
      return Object.keys(properties).reduce((actual, next) => actual.concat(` ${next}`), "");
    }

    function object2getParameters(object){

      let propertiesStr = "";
      for (key of Object.keys(object)) {
          let prop = `${key}=${object[key]}&`;
          propertiesStr += prop;
      }

      propertiesStr = propertiesStr.substr(0, propertiesStr.length-1);

      return propertiesStr;
    }
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

我需要为所有容器中的所有 blob 更新 属性 cache-control。如果需要更多信息,请告诉我。谢谢。

您要调用的函数是 setBlobProperties。这将为指定的 blob 或快照设置 user-defined 属性。

这是一个示例代码片段,您可以在您的应用程序中使用它来保存新的 Cache-Control 值。

var properties = {};
properties.cacheControl = 'max-age=2592000';

blobService.setBlobProperties('<containerName>', '<blobName>', properties, function(error, result, response) {  
  if(!error) {
    console.log('blob properties setted!');
  }     
})

代码将为 Blob 设置以下属性。