IFormFile 使用 vs2022 将 null 值传递给 asp.netcore RazorPage 6.0 中的 Action

问题描述 投票:0回答:1

我使用 VisualStudio2022 创建了 dotnetCore6.0 MVC RazorePage 解决方案, 我有一个页面提供一个 excel 文件并将被插入到数据库中, 不幸的是,每当尝试发送文件时,操作中的文件都是 NULL! 我的 httpcontext.Request.Form 也有错误! 这是我的 cshtml :

<div class = "card">
    <div class="card-header"> Upload Products Excel File   </div>
    <div class="card-body" >
        <form asp-action="BulkInsert"  enctype="multipart/form-data"  >
            <div class="form-group" >
                <lable> Excel File </lable>
                <input name="excelFile" id="excelFile" type="file" accept=".xlsx, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />
            </div>
            <div class="form-group">
                <button class="btn-primary btn-success" >
                    Send File
                </button>
            </div>

        </form>

    </div>
</div>

这就是cs方法

[HttpPost]
    public async Task<IActionResult> BulkInsert(IFormFile excelFile)
    {
        // First Add Package  'dotnet add package ExcelDataReader' 
        // then using MemoryStream to read Excel data

        var formFile = HttpContext.Request.Form.Files[0];
        var aa = HttpContext;
        List<ProductViewModel> products = new List<ProductViewModel>();

        using (var ms = new MemoryStream())
        {
            excelFile.CopyTo(ms);
            bool firstRow = true;

            using (var reader = ExcelReaderFactory.CreateReader(ms))
            {
                do
                {
                    while (reader.Read())
                    {
                        if (firstRow)// Breakes First Row
                        {
                            firstRow = false;
                            continue;

                        }
                        var product = new ProductViewModel()
                        {
                            ProductName = reader[0].ToString(),
                            CategoryID = Convert.ToInt32(reader[1]),
                            SupplierID = Convert.ToInt32(reader[2]),
                            UnitPrice = Convert.ToDouble(reader[3]),
                        };
                        products.Add(product);
                    }
                    
                } 
                while(reader.NextResult());
            }

        }
        return View(nameof(Index));
    }

}
asp.net-core-mvc razor-pages visual-studio-2022 asp.net-core-6.0 iformfile
1个回答
0
投票

您需要在表单元素中指定

method="post"

<form asp-action="BulkInsert"  enctype="multipart/form-data"  method="post">

© www.soinside.com 2019 - 2024. All rights reserved.