React UI截图上传Azure Blob Storage遇401认证失败求助
排查Azure Blob Storage上传截图时的401认证失败问题
我正在开发将React UI截图上传至Azure Blob Storage的功能,但上传截图时遇到了401认证失败的问题。以下是相关代码和错误信息:
相关代码
./src/captureError.js
export const getCapturedImageBlob = async (container) => { const screenshot = await html2canvas(container); return screenshot; } export const uploadImageToBlobStorage = (screenshot, connection_string, container_name, blob_name) => { screenshot.toBlob(blob => { console.log(blob); const blobServiceClient = new BlobServiceClient(connection_string); const containerClient = blobServiceClient.getContainerClient(container_name); const blobClient = containerClient.getBlockBlobClient(blob_name); blobClient.uploadData(blob); }) }
./src/App.js
const screenshot = await getCapturedImageBlob(document.querySelector("#root")); uploadImageToBlobStorage(screenshot, 'https://{Account Name}.blob.core.windows.net', {Container Name}, {Blob name});
错误信息

PUT https://{Account Name}.blob.core.windows.net/{Container Name}/{Blob Name}?{Account Key} 401 (Server failed to authenticate the request. Please refer to the information in the www-authenticate header.)
排查与解决方法
1. 连接字符串格式错误
你当前传入的connection_string是存储账户的端点URL,但BlobServiceClient要求传入完整的存储账户连接字符串,格式如下:
DefaultEndpointsProtocol=https;AccountName={你的账户名};AccountKey={你的账户密钥};EndpointSuffix=core.windows.net
直接传入端点URL会导致客户端无法完成身份验证,这是401错误的核心原因。
2. 验证账户密钥有效性
- 确认你使用的存储账户密钥是正确的,可在Azure门户的存储账户「访问密钥」页面获取。
- 检查密钥是否过期或被重置,若有更新需替换为最新密钥。
3. 容器访问权限检查
- 如果容器设置为私有访问级别,必须使用正确的认证信息才能上传;若需临时测试,可将容器访问级别改为「Blob(匿名读取Blob)」(生产环境不建议此配置)。
4. 修正代码异步逻辑(非401直接原因,但需优化)
原uploadImageToBlobStorage函数未处理异步操作的Promise,可能导致调用流程混乱。修正后的代码如下:
修正后的./src/captureError.js
export const getCapturedImageBlob = async (container) => { const screenshot = await html2canvas(container); return screenshot; } export const uploadImageToBlobStorage = async (screenshot, connection_string, container_name, blob_name) => { return new Promise((resolve, reject) => { screenshot.toBlob(async (blob) => { if (!blob) { reject(new Error('截图转Blob失败')); return; } try { const blobServiceClient = new BlobServiceClient(connection_string); const containerClient = blobServiceClient.getContainerClient(container_name); const blobClient = containerClient.getBlockBlobClient(blob_name); const uploadResult = await blobClient.uploadData(blob); resolve(uploadResult); } catch (err) { reject(err); } }); }); }
修正后的./src/App.js调用
const screenshot = await getCapturedImageBlob(document.querySelector("#root")); try { await uploadImageToBlobStorage(screenshot, 'DefaultEndpointsProtocol=https;AccountName={你的账户名};AccountKey={你的账户密钥};EndpointSuffix=core.windows.net', '{容器名称}', '{Blob名称}'); console.log('上传成功'); } catch (err) { console.error('上传失败:', err); }
5. 额外检查项
- 确认存储账户名、容器名、Blob名无拼写错误,URL中的特殊字符已正确编码。
- 若为浏览器端上传,需在Azure门户配置存储账户的CORS规则,允许你的React应用域名发起跨域请求。
内容的提问来源于stack exchange,提问作者Branch
相关产品推荐
相关产品推荐

