You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在ReactJs中从Azure Storage文件共享展示文件列表并下载

在React应用中展示Azure文件共享的文件列表并实现下载功能

1. 安装Azure文件共享SDK

在React项目根目录执行以下命令安装官方SDK:

npm install @azure/storage-file-share

2. 准备安全的访问凭证

绝对不要在前端代码中硬编码存储账户密钥,推荐使用共享访问签名(SAS):

  • 登录Azure门户,找到你的storage1存储账户
  • 进入「共享访问签名」页面,选择「文件」服务,勾选读取权限(如需其他操作可额外勾选),设置合理的过期时间
  • 生成SAS令牌后,复制完整的SAS参数串(以?开头的部分)

3. 编写React组件实现功能

创建AzureFileList.js组件,实现文件列表拉取和下载逻辑:

import { ShareServiceClient } from "@azure/storage-file-share";
import { useEffect, useState } from "react";

const AzureFileList = () => {
  const [files, setFiles] = useState([]);
  const [isLoading, setIsLoading] = useState(true);

  // 替换为你的存储账户名和生成的SAS令牌
  const STORAGE_ACCOUNT = "storage1";
  const SAS_TOKEN = "你的SAS令牌(例如:?sv=2023-11-03&ss=f&srt=sco&sp=r&se=2024-12-31T23:59:59Z&st=2024-01-01T00:00:00Z&spr=https&sig=xxxxxx)";

  useEffect(() => {
    const loadFiles = async () => {
      try {
        // 初始化文件服务客户端
        const serviceClient = new ShareServiceClient(
          `https://${STORAGE_ACCOUNT}.file.core.windows.net${SAS_TOKEN}`
        );
        // 获取目标文件共享
        const shareClient = serviceClient.getShareClient("share1");
        // 获取根目录客户端(文件在子目录的话,替换为对应目录名)
        const dirClient = shareClient.getDirectoryClient("");
        
        // 遍历目录下所有文件
        const fileList = [];
        for await (const item of dirClient.listFilesAndDirectories()) {
          if (item.kind === "file") {
            fileList.push({
              name: item.name,
              downloadUrl: `${dirClient.url}/${item.name}${SAS_TOKEN}`
            });
          }
        }
        setFiles(fileList);
      } catch (err) {
        console.error("加载文件失败:", err);
      } finally {
        setIsLoading(false);
      }
    };

    loadFiles();
  }, []);

  // 触发文件下载
  const downloadFile = (url, fileName) => {
    const downloadLink = document.createElement("a");
    downloadLink.href = url;
    downloadLink.download = fileName;
    document.body.appendChild(downloadLink);
    downloadLink.click();
    document.body.removeChild(downloadLink);
  };

  if (isLoading) {
    return <div>加载文件列表中...</div>;
  }

  return (
    <div className="file-list-container">
      <h3>文件共享列表</h3>
      <ul>
        {files.map((file, idx) => (
          <li key={idx} style={{ margin: "8px 0" }}>
            <span>{file.name}</span>
            <button 
              onClick={() => downloadFile(file.downloadUrl, file.name)}
              style={{ marginLeft: "12px", padding: "4px 8px" }}
            >
              下载
            </button>
          </li>
        ))}
      </ul>
    </div>
  );
};

export default AzureFileList;

4. 生产环境注意事项

  • 安全优化:前端直接使用SAS令牌存在被窃取的风险,生产环境建议搭建后端API,由后端处理Azure存储的请求,前端仅调用后端接口获取文件列表和下载链接。
  • 子目录适配:如果文件存储在share1的子目录中,修改getDirectoryClient的参数为对应子目录名称即可。
  • 权限控制:SAS令牌的权限和过期时间要严格设置,避免过度授权或长期有效。

内容的提问来源于stack exchange,提问作者tiger t

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 04:10:26