如何在HTML下拉栏中列出Azure Blob容器内容供选择?
解决Azure Storage Blob容器文件列表前端展示问题
第一步:搞定CORS跨域错误
你现在卡壳的核心原因是Azure Storage没配置CORS规则,浏览器直接拦截了跨域请求。按以下步骤配置:
- 登录Azure门户,找到你的Storage账户
- 左侧菜单选「资源共享(CORS)」,在「Blob服务」标签下新增规则:
- 允许的来源:本地测试可填
*(生产环境务必指定具体前端域名,别用通配符) - 允许的方法:勾选
GET(列文件、下载都需要) - 允许的标头:填
* - 公开的标头:填
* - 最大年龄(秒):设为
86400(一天)
- 允许的来源:本地测试可填
- 保存配置,等几分钟生效
第二步:修复XMLHttpRequest实现代码
你原代码有变量名写错、同步请求不规范的问题,下面是修复后的完整HTML示例:
<!DOCTYPE html> <html> <head> <title>Blob文件下载器</title> </head> <body> <select id="fileSelect"></select> <button onclick="downloadSelectedFile()">下载</button> <script> // 替换成你的Storage信息 const containerUrl = 'https://account-name.blob.core.windows.net/container-name'; const sasToken = 'your-sas-token'; // 注意不要带开头的? function listFiles() { const url = `${containerUrl}?${sasToken}&restype=container&comp=list`; const req = new XMLHttpRequest(); req.open('GET', url, true); req.onload = function() { if (req.status === 200) { const xml = req.responseXML; const blobElements = xml.getElementsByTagName('Blob'); const select = document.getElementById('fileSelect'); select.innerHTML = ''; // 清空旧选项 for (let i = 0; i < blobElements.length; i++) { const blobName = blobElements[i].getElementsByTagName('Name')[0].textContent; const option = document.createElement('option'); option.value = blobName; option.textContent = blobName; select.appendChild(option); } } else { alert('加载文件列表失败:' + req.statusText); } }; req.onerror = function() { alert('请求出错,请检查CORS配置和SAS令牌'); }; req.send(); } function downloadSelectedFile() { const select = document.getElementById('fileSelect'); const selectedFile = select.value; if (!selectedFile) { alert('请选择一个文件'); return; } // 构造下载链接,新窗口打开 const downloadUrl = `${containerUrl}/${encodeURIComponent(selectedFile)}?${sasToken}`; window.open(downloadUrl); } // 页面加载自动拉取文件列表 window.onload = listFiles; </script> </body> </html>
第三步:更稳定的官方SDK实现
用Azure官方的@azure/storage-blob SDK比自己解析XML更靠谱,步骤如下:
- 页面引入SDK:
<script src="https://cdn.jsdelivr.net/npm/@azure/storage-blob@12.17.0/dist/umd/storageBlob.min.js"></script>
- 替换列表文件的代码:
async function listFiles() { try { const containerClient = new azure.storage.blob.ContainerClient(`${containerUrl}?${sasToken}`); const select = document.getElementById('fileSelect'); select.innerHTML = ''; for await (const blob of containerClient.listBlobsFlat()) { const option = document.createElement('option'); option.value = blob.name; option.textContent = blob.name; select.appendChild(option); } } catch (error) { alert('加载文件列表失败:' + error.message); } } // 页面加载时调用(async函数需包装) window.onload = () => listFiles();
下载函数和之前保持一致即可。
注意事项
- SAS令牌必须包含
list和read权限(生成SAS时勾选这两项) - 生产环境CORS允许的来源不要用
*,指定你的前端域名 - 本地测试别直接用
file://打开HTML,建议用本地服务器(比如python -m http.server)访问
内容的提问来源于stack exchange,提问作者bowlingh23
相关产品推荐
相关产品推荐

