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);
})();

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

查看所有标签

猜你喜欢:

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

Structure and Interpretation of Computer Programs - 2nd Edition

Structure and Interpretation of Computer Programs - 2nd Edition

Harold Abelson、Gerald Jay Sussman / The MIT Press / 1996-7-25 / USD 145.56

Structure and Interpretation of Computer Programs has had a dramatic impact on computer science curricula over the past decade. This long-awaited revision contains changes throughout the text. Ther......一起来看看 《Structure and Interpretation of Computer Programs - 2nd Edition 》 这本书的介绍吧!

SHA 加密
SHA 加密

SHA 加密工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

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

HSV CMYK互换工具