Willin: Azure Node.js Blob文件上传

栏目: 编程工具 · 发布时间: 7年前

内容简介:Willin: Azure Node.js Blob文件上传

对官方文档一些需要额外注意的细节整理

azure-storage官方文档: http://azure.github.io/azure-storage-node/

建立连接

有3种方式(文档中未提及):

1. 通过环境变量

AZURE_STORAGE_CONNECTION_STRING="valid storage connection string" node app.js

应用程序内:

const azure = require('azure-storage');
const blobService = azure.createBlobService();
// code here

2.连接字符串

const azure = require('azure-storage');
const blobService = azure.createBlobService('connectionString'); // 类似: DefaultEndpointsProtocol=https;AccountName=*****;AccountKey=*****;EndpointSuffix=*****.core.chinacloudapi.cn
// code here

3.账号+密钥

const azure = require('azure-storage');
const blobService = azure.createBlobService('storageAccount', 'storageAccessKey', 'storageHost'); 
// code here

上传示例

因为POST请求接收到的大部分是Stream.所以采用Sream的方式上传.

// azure.js
const azure = require('azure-storage');
const { getDefer } = require('@dwing/common');

const blobService = azure.createBlobService('accountName', 'accessKey', 'host');

exports.createBlockBlobFromStream = (container, filename, blob) => {
  const deferred = getDefer();
  blob.on('error', (err) => {
    deferred.reject(err);
  });
  blob.pipe(blobService.createWriteStreamToBlockBlob(container, filename));
  blob.on('end', () => {
    deferred.resolve(1);
  });
  return deferred.promise;
};

测试代码:

// demo.js
const { createBlockBlobFromStream } = require('./azure');
const fs = require('fs');
const path = require('path');

const stream = fs.createReadStream(path.join(__dirname, '/testfile'));

(async() => {
  const result = await createBlockBlobFromStream('container', 'filename', stream);
  console.log(result);
})();

在 AirX 项目中的实际使用:

https://github.com/AirDwing/node-airx-sdk

const SDK = require('@airx/sdk');
const fs = require('fs');

const sdk = new SDK({
  SecretId: 'xxxx',
  SecretKey: 'xxxx'
});

(async() => {
  const result = await sdk.upload({
    auth: 'xxxx',
    type: 'orgverify',
    file: fs.createReadStream('PATH/TO/xxx.jpg') // 注意这里, 本地文件可以用 path.join 拼装地址,或者直接用Stream
  });
  console.log(result);
})();

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Machine Learning

Machine Learning

Kevin Murphy / The MIT Press / 2012-9-18 / USD 90.00

Today's Web-enabled deluge of electronic data calls for automated methods of data analysis. Machine learning provides these, developing methods that can automatically detect patterns in data and then ......一起来看看 《Machine Learning》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具