简体   繁体   English

上传 asp.net 内核 3.1 Razor

[英]Uploading asp.net core 3.1 Razor

I'm trying to upload files in ASP.NET core 3.1, but in my Post I'm not receiving the file.我正在尝试在 ASP.NET 核心 3.1 中上传文件,但在我的帖子中我没有收到文件。

That count = 0 is what I always get.计数= 0是我总是得到的。

@cshtml @cshtml

 <input asp-for="app.FormFile" id="input-2" name="input2[]" type="file" class="file" multiple data-show-upload="true" data-show-caption="true">

@cshtml.cs @cshtml.cs

public async Task<IActionResult> OnPostAsync(List<IFormFile> files)
{
    long size = files.Sum(f => f.Length);

    foreach (var formFile in files)
    {
        if (formFile.Length > 0)
        {
            var filePath = Path.GetTempFileName();

            using (var stream = System.IO.File.Create(filePath))
            {
                await formFile.CopyToAsync(stream);
            }
        }
    }

    // Process uploaded files
    // Don't rely on or trust the FileName property without validation.

    return Ok(new { count = files.Count, size });
}

In ASP.NET core 2.0 this worked fine?在 ASP.NET 核心 2.0 中这工作正常吗? What's wrong?怎么了?

The param name is files , but you're explicitly setting the input name to input2[] , so they don't match up.参数名称是files ,但您将输入名称明确设置为input2[] ,因此它们不匹配。 ASP.NET Core isn't going to try to interpret that you've uploaded some files so you probably want them to go on this param. ASP.NET 核心不会试图解释你已经上传了一些文件,所以你可能希望他们在这个参数上到 go。 If it can't find something to bind the data to (by name), it's just going to discard it and move on.如果它找不到将数据绑定到(按名称)的东西,它只会丢弃它并继续前进。

The name should files so it matches up to the param name: name="files" .该名称应该是files ,因此它与参数名称匹配: name="files"

even if I pass the name it still came with count = 0 <input asp-for="Laudos.FormFile" id="files" name="files" type="file" class="file" multiple data-show-upload="true" data-show-caption="true">即使我传递了名称,它仍然带有 count = 0 <input asp-for="Laudos.FormFile" id="files" name="files" type="file" class="file" multiple data-show-upload="true" data-show-caption="true">

You can try to specify an encoding type (enctype) of multipart/form-data for your <form> tag, like below.您可以尝试为<form>标签指定multipart/form-data的编码类型 (enctype),如下所示。

<form method="post" enctype="multipart/form-data">
    <input asp-for="Laudos.FormFile" id="input-2" name="files" type="file" class="file" multiple data-show-upload="true" data-show-caption="true">
    <input type="submit">
</form>

Test Result测试结果

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM