【问题标题】:Upload a File object to azure storage from react js / node js从 react js / node js 将文件对象上传到天蓝色存储
【发布时间】:2021-01-16 02:15:22
【问题描述】:

我正在尝试浏览文件并将其直接从 react js / node js 应用程序上传到 azure 存储帐户。尝试了几个模块“azure-storage”和“@azure/storage-blob”。我可以手动创建/上传包含一些内容的 blob 并将其上传到 azure 存储帐户,但我找不到上传通过“浏览 - 选择文件(输入类型 = 文件)选择的文件”的方法。

请给我一个好的方法。

以下是示例代码: 这里的 'file' 是通过 ma​​terial-ui-dropzone -- DropzoneArea

浏览的 File 对象
import {BlobServiceClient, StorageSharedKeyCredential} from '@azure/storage-blob';

const sharedKeyCredential = new StorageSharedKeyCredential(azureStorageAccount, azureStorageAccessKey);
const serviceClient = new BlobServiceClient(
  // When using AnonymousCredential, following url should include a valid SAS
  `https://${azureStorageAccount}.blob.core.windows.net`,
  sharedKeyCredential
);

let containerExists = false;
for await (const container of containerIter) {
  if (container.name === containerName) {
    containerExists = true;
    break;
  }
}
const containerClient = serviceClient.getContainerClient(containerName);
if (!containerExists) {
  const createContainerResponse = await containerClient.create();
  console.log('Container was created successfully', createContainerResponse.requestId);
}

// below working fine
const content = 'samle content';
const blobName = 'sample.txt';
const blockBlobClient = containerClient.getBlockBlobClient(blobName);
const uploadBlobResponse = await blockBlobClient.upload(content, content.length);
console.log(`Upload block blob ${blobName} successfully`, uploadBlobResponse.requestId);

// NOT WORKING : here file is a File object
const blobName = file.name;
console.log(blobName);
const blockBlobClient = containerClient.getBlockBlobClient(blobName);
const uploadBlobResponse = await blockBlobClient.uploadBrowserData(file);
console.log(`Upload block blob ${file.name} successfully`, uploadBlobResponse.clientRequestId);

提前致谢。

【问题讨论】:

  • 我认为这个教程应该是一个很好的例子。它应该对你有所帮助。

标签: node.js reactjs azure-storage azure-blob-storage azure-storage-account


【解决方案1】:

您可以先阅读此博客。

Upload to Azure Blob Storage with React

我查看了文档并再次尝试。下面的gif动画应该就是你想要的结果了。

我引用了官方的示例代码,因为有些依赖版本有要求,下载后不能直接使用。我修复了这个问题并将其上传到我自己的 github,you can download it。

当您需要在项目中使用时,请仔细阅读源代码并修改配置。

【讨论】:

    猜你喜欢
    • 2021-08-29
    • 2021-12-26
    • 2022-10-16
    • 1970-01-01
    • 2020-11-29
    • 2013-07-29
    • 2015-09-09
    • 2015-10-25
    • 2021-06-18
    相关资源
    最近更新 更多