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

如何将HTML文件输入数据传递到Blazor Razor Components代码页并解决空值问题

问题核心成因
  1. 浏览器安全沙箱限制:所有Web应用(包括Blazor PWA)都无法直接获取用户本地文件的完整路径,input type="file"控件只会暴露文件名,不会返回真实本地存储路径,你尝试用File.Open直接读路径的逻辑不符合Web端安全规则,完全无法实现。
  2. 代码缺少文件绑定逻辑:前端的input控件没有和后端C#代码做任何关联,你代码里写死的txtFileName = "txtFileName"是固定字符串,和用户选中的文件没有任何关系,自然读不到对应文件。
修复方案

Blazor官方已经提供了专门的InputFile组件处理文件选择场景,直接用该组件获取文件流即可,不需要读取本地路径。

1. 修改 Index.razor

@page "/"
@using Microsoft.AspNetCore.Components.Forms

<table>
    <tr>
        <td>
            <label for="lblPFile">Progyny File : </label>
        </td>
        <td>
            <InputFile id="lblPFile" @bind-File="SelectedExcelFile" accept=".xls,.xlsx" />
        </td>
    </tr>
</table>
<PageTitle>Progyny File Information</PageTitle>
<h1>Progyny File </h1>
<button class="btn btn-primary" @onclick="ProcessFile" disabled="@(SelectedExcelFile == null)">Process File</button>
<p>
    <textarea> @ShowMessage </textarea>
</p>

2. 修改 IndexPartialClass.razor.cs

using System.IO;
using System.Text;
using ExcelDataReader;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;

namespace TRY2.Pages
{
    public partial class Index
    {
        private IBrowserFile? SelectedExcelFile { get; set; }
        private string ShowMessage = "";

        public void ProcessFile()
        {
            if (SelectedExcelFile == null)
            {
                ShowMessage = "请先选择Excel文件";
                return;
            }

            // 注册编码提供器,避免读取旧版xls文件时报编码错误
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            // 直接读取浏览器提供的文件流,最大允许10MB,可根据需求调整
            using (var stream = SelectedExcelFile.OpenReadStream(maxAllowedSize: 10 * 1024 * 1024))
            {
                using (var reader = ExcelReaderFactory.CreateReader(stream))
                {
                    do
                    {
                        while (reader.Read()) // 逐行读取
                        {
                            for (int column = 0; column < reader.FieldCount; column++)
                            {
                                var val = reader.GetValue(column);
                                if (val != null)
                                {
                                    ShowMessage += val.ToString() + Environment.NewLine;
                                }
                            }
                        }
                    } while (reader.NextResult()); // 切换下一个工作表
                }
            }
        }
    }
}
注意事项
  • InputFile的OpenReadStream默认最大允许文件大小为512KB,处理大文件需要主动修改maxAllowedSize参数
  • 不要尝试任何获取本地文件路径的操作,Web端的文件处理完全基于浏览器暴露的文件流实现
  • 如果需要持久化文件内容,可以把流读到内存或者上传到后端服务器存储,不要尝试直接操作本地磁盘

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 02:54:03