【发布时间】:2021-06-02 17:47:02
【问题描述】:
我希望以流的形式将文件上传到 Azure 存储,但我不想使用 Azure SDK,而是想以更通用的方式使用 REST API而不是 BlobServiceClient。
有没有办法做到这一点? 可以在此处找到相同的参考链接:
但是这里提到的链接提出了一个使用Azure SDK 的解决方案。我想这样做 没有 Azure SDK
代码如下:
const CryptoJS = require("crypto-js");
const request = require("request");
const fs = require("fs");
const account = process.env.ACCOUNT_NAME || "";
const key = process.env.ACCOUNT_KEY || "";
const containerName = "demo";
const blobName = "dummyfile.txt";
var strTime = new Date().toUTCString();
// read file to Stream
var filePath = `${__dirname}/README.md`;
const readStream = fs.createReadStream(filePath);
var stat = fs.statSync(filePath);
string_params = {
verb: "PUT",
"Content-Encoding": "",
"Content-Language": "",
"Content-Length": stat.size,
"Content-MD5": "",
"Content-Type": "application/octet-stream",
Date: "",
"If-Modified-Since": "",
"If-Match": "",
"If-None-Match": "",
"If-Unmodified-Since": "",
Range: "",
CanonicalizedHeaders:
"x-ms-blob-type:BlockBlob\nx-ms-date:" +
strTime +
"\nx-ms-version:" +
"2020-04-08\n",
CanonicalizedResource: `/${account}/${containerName}/${blobName}`,
};
var strToSign = `${string_params["verb"]}\n${string_params["Content-Encoding"]}\n${string_params["Content-Language"]}\n${string_params["Content-Length"]}\n${string_params["Content-MD5"]}\n${string_params["Content-Type"]}\n${string_params["Date"]}\n${string_params["If-Modified-Since"]}\n${string_params["If-Match"]}\n${string_params["If-None-Match"]}\n${string_params["If-Unmodified-Since"]}\n${string_params["Range"]}\n${string_params["CanonicalizedHeaders"]}${string_params["CanonicalizedResource"]}`;
var secret = CryptoJS.enc.Base64.parse(key);
var hash = CryptoJS.HmacSHA256(strToSign, secret);
var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
var auth = `SharedKey ${account}:` + hashInBase64;
const options = {
url: `https://${account}.blob.core.windows.net/${containerName}/${blobName}`,
headers: {
Authorization: auth,
"x-ms-blob-type": "BlockBlob",
"x-ms-date": strTime,
"x-ms-version": "2020-04-08",
"Content-Type": "application/octet-stream",
"Content-Length": stat.size,
},
body: readStream,
};
function callback(error, response, body) {
console.log(response.statusCode);
console.log(response.statusMessage);
if (!error && response.statusCode == 200) {
console.log(error);
console.log(response);
console.log(body);
}
}
request.put(options, callback);
我得到的错误是:
TypeError: Cannot read property 'statusCode' of undefined
编辑:问题已由 Pamela 的代码解决 + 我发现的问题是初始化 .env 变量时出错。
【问题讨论】:
标签: javascript node.js azure azure-blob-storage rest