简体   繁体   中英

Azure storage avoid uploading file if name already exists

I am trying to upload a file to azure storage. I have it working using the package multer-azure however if I upload a file with the same name of one already stored in the storage, the first one will get replaced.

From docs it seems like I need to add a ETagMatch but I am not sure where this should go.

https://azure.github.io/azure-storage-node/global.html#AccessConditions

My code:

      var upload = multer({
        storage: multerAzure({
            account: STORAGE_ACCOUNT_NAME, //The name of the Azure storage account
            key: ACCOUNT_ACCESS_KEY, //A key listed under Access keys in the storage account pane
            container: 'demo',  //Any cntainer name, it will be created if it doesn't exist
            blobPathResolver:  (_req, file, callback) => {
                let path;
                if(_req.body.pathToFile) {
                    path = `${organization}/${_req.body.pathToFile}/${file.originalname}`
                } else {
                    path = `${organization}/${file.originalname}`;
                }
                // var blobPath = yourMagicLogic(req, file); //Calculate blobPath in your own way.
                callback(null, path);
            }
        })
    }).single('file')

    upload(req, res, function (err) {
        if (err instanceof multer.MulterError) {
            return res.status(500).json(err)
        } else if (err) {
            return res.status(500).json(err)
        }
        return res.status(200).send(req.file)
    })

If the blob already exists on the service, it will be overwritten. You can simply use doesBlobExist method of the SDK to check if a blob exists in a path in NodeJS. If not exist, you could upload a file to Azure storage.

var blobService = azure.createBlobService(storageAccount, accessKey);
blobService.doesBlobExist('azureblob', 'xxx/a.json', function(error, result) {
  if (!error) {
    if (result.exists) {
      console.log('Blob exists...');
    } else {
      console.log('Blob does not exist...');
    }
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM