首页 > 解决方案 > 无法上传到 Blob 存储,缺少 Access-Control-Allow-Origin 标头

问题描述

在浏览器中使用 @azure/storage-blob 模块,无法直接上传到 azure 存储。它抱怨缺少请求标头。上传是在作为 Office 插件运行的 ReactJS 应用程序中完成的。

根据 Microsoft 的要求,已在 Blob 的存储帐户上启用了 CORS。

我尝试找到一种添加自定义 HTTP 标头的方法,但是没有一个有效。

这是上传代码

import { Credential, BlobServiceClient} from "@azure/storage-blob/browser/azure-storage-blob.min.js";

export function uploadToStorage(storageAccountName: string, storageAccountKey: string, file: SelectedFile) {
    return async (dispatch) => {
        try {
            const account = storageAccountName;
            const accountKey = storageAccountKey;
            const sharedKeyCredential = new Credential(account, accountKey);
            const blobServiceClient = new BlobServiceClient(
                `https://${account}.blob.core.windows.net`,
                sharedKeyCredential
            );
            const containerClient = blobServiceClient.getContainerClient("container-name");
            const blobClient = containerClient.getBlobClient(file.name);
            const blockBlobClient = blobClient.getBlockBlobClient();
            const uploadBlobResponse = await blockBlobClient.uploadBrowserData(file.data, {
                maxSingleShotSize: 4 * 1024 * 1024
              }, { "blobHTTPHeaders": { "blobContentType": file.mimeType } });
        }
        catch (error) { 
            console.error(error);
        }
    }
}

Chrome 调试器的错误如下:

从源“ https://localhost:3000 ”访问“ https://somestorageaccountsomewhere.blob.core.windows.net/blablablacontainer/Somefile-2018.5-en.docx ”中的 XMLHttpRequest已被 CORS 策略阻止:对预检的响应请求未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。

标签: azureazure-storageazure-blob-storageazure-sdk

解决方案


推荐阅读