对于我的 Node js 项目,我使用了 AWS S3 存储桶并使用 AWS SDK 从前端上传文件。
同样,我的文件存储现在需要迁移到 Azure Blob 存储
有没有办法从客户端直接上传到Azure Blob存储?
使用堆栈:Node Js(使用 EJS 作为模板引擎的 Javascript)
我尝试通过像这样传递 BlobServiceClient 来使用 browserify 构建 bundle ,
var { BlobServiceClient } = require("@azure/storage-blob");
window.BlobServiceClient = BlobServiceClient;
但它显示错误,例如 TypeError: BlobServiceClient is not a constructor
最后,我想用 Azure blob 存储功能替换 S3 存储桶上传功能,并且我想需要来自“@azure/storage-blob”的 BlobServiceClient,这样我就不必更改太多代码在前端。
请提供将 azure storage npm 包集成到浏览器中的解决方案。
最佳答案
我在自己的环境中进行了尝试,并成功使用浏览器将文件上传到 Azure Blob 存储中。
开始之前,您需要安装两个软件包。
1.npm install @azure/storage-blob
2.npm install parcel
Index.js
const { BlobServiceClient } = require("@azure/storage-blob");
const selectButton = document.getElementById("select-button");
const fileInput = document.getElementById("file-input");
const blobSasUrl = "<your sas url >";
const blobServiceClient = new BlobServiceClient(blobSasUrl);
const containerName = "test";
const containerClient = blobServiceClient.getContainerClient(containerName);
const uploadFiles = async () => {
try {
const promises = [];
for (const file of fileInput.files) {
const blockBlobClient = containerClient.getBlockBlobClient(file.name);
promises.push(blockBlobClient.uploadData(file));
}
await Promise.all(promises);
alert("Done.");
}
catch (error) {
alert(error.message);
}
}
selectButton.addEventListener("click", () => fileInput.click());
fileInput.addEventListener("change", uploadFiles);
Index.html:
<!DOCTYPE html>
<html>
<body>
<button id="select-button">Select and upload files</button>
<input type="file" id="file-input" multiple style="display: none;" />
<script type="module" src="index.js"></script>
</body>
</html>
package.json
{
"name": "blob-quickstart-v12",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "parcel ./index.html"
},
"keywords": [],
"author": "",
"license": "ISC",
"browserslist": [
"last 1 Edge version",
"last 1 Chrome version",
"last 1 Firefox version",
"last 1 safari version",
"last 1 webkit version"
],
"dependencies": {
"@azure/storage-blob": "^12.12.0",
"parcel": "^2.8.0"
},
"devDependencies": {
"buffer": "^5.7.1"}
}
您可以通过检查下图获取Blob SAS-URL
。
控制台:
浏览器:
我复制了网址
并将其粘贴到浏览器中,它起作用了。
上传后,它在浏览器中反射(reflect)完成。
门户:
引用:
Get started with Azure Blob Storage and JavaScript - Azure Storage | Microsoft Learn
关于javascript - Azure Blob 存储客户端上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74395934/