将Cache-Control和Expires标头添加到Azure Blob存储节点JS

时间:2017-01-16 15:49:52

标签: javascript node.js azure azure-storage azure-storage-blobs

我正在使用Azure存储来提供静态文件blob,但我希望在提供服务时为文件/ blob添加Cache-Control和Expires标头以降低带宽成本。

但我使用的是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。如果需要更多信息,请告诉我。韩国社交协会。

1 个答案:

答案 0 :(得分:4)

您要调用的功能是setBlobProperties。这将为指定的blob或快照设置用户定义的属性。

以下是一个示例代码段,您可以在应用程序中使用该示例代码段来保留新的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设置以下属性。

enter image description here