【问题标题】:How do I post an IFormFile in ASP.Net Core 2.0 Razor Pages?如何在 ASP.Net Core 2.0 Razor 页面中发布 IFormFile?
【发布时间】:2018-11-24 11:39:48
【问题描述】:

我正在使用 ASP.Net Core 2.0 和 Razor Pages 处理应用程序。我一直在关注有关如何将文件上传到 Azure blob 存储的 Microsoft Docs,但到目前为止我无法让它工作。

我有两个独立的模型类。一个用于文件上传,一个用于 Word。

文件上传类:

public class WordUpload
{
    public IFormFile SoundFile { get; set; }
    public IFormFile SoundFileSentence { get; set; }
}

其他类:

public class Word
{
    public int ID { get; set; }
    public string Answer { get; set; }
    public string AlternativeAnswer { get; set; }
    public string Hint { get; set; }
    public int Length { get; set; }
    public int Vowels { get; set; }
    public string Language { get; set; }
    public string Category { get; set; }
    public int Module { get; set; }
    public string Difficulty { get; set; }
    public string Sound { get; set; }
    public string SoundSentence { get; set; }
}

带有未传递的 WordUpload.SoundFile 的页面。这就是问题所在,因为它总是返回 null。

public class CreateModel : PageModel
{
    private readonly Data.ApplicationDbContext _context;
    private readonly IWordRepository _wordRepository;

    public CreateModel(Data.ApplicationDbContext context, IWordRepository wordRepository)
    {
        _context = context;
        _wordRepository = wordRepository;
    }

    /// <summary>
    /// OnGet triggers when the page is opened
    /// </summary>
    /// <returns></returns>
    public IActionResult OnGet()
    {
        Word = new Word
        {
            Answer = "",
            AlternativeAnswer = "",
            Hint = "Hint",
            Length = 0,
            Vowels = 0,
            Language = "DK",
            Category = "",
            Module = 0,
            Difficulty = "",
            Sound = "",
            SoundSentence = ""
        };

        return Page();
    }

    [BindProperty]
    public WordUpload WordUpload { get; set; }

    [BindProperty]
    public Word Word { get; set; }

    /// <summary>
    /// Posts the data to the database async
    /// </summary>
    /// <returns></returns>
    public async Task<IActionResult> OnPostAsync()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }

        // Get the number of vowels in the word
        Word.Vowels = _wordRepository.NumberOfVowels(Word.Answer);

        // Save the length
        Word.Length = Word.Answer.Length;

        // upload file to blob storage
        Word.Sound = _wordRepository.UploadAudio(WordUpload.SoundFile);

        // save to db
        _context.Word.Add(Word);
        await _context.SaveChangesAsync();
        return RedirectToPage("./Index");
    }
}

还有视图-页面:

@page
@model Fabetio.Web.Pages.Words.CreateModel

@{
    ViewData["Title"] = "Create";
}

<div class="container-fluid darkblue-background">

    <br>
    <br>

    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <div class="task--card">

                <div class="dasboard--title">
                    <h1>@ViewData["Title"]</h1>
                    <p class="subtitle">Subtitle.</p>
                </div>

                <form method="post">
                    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                    <input type="hidden" asp-for="Word.ID" />
                    <div class="form-group">
                        <label asp-for="Word.Answer" class="control-label"></label>
                        <input asp-for="Word.Answer" class="form-control" />
                        <span asp-validation-for="Word.Answer" class="text-danger"></span>
                    </div>
                    <div class="form-group">
                        <label asp-for="Word.AlternativeAnswer" class="control-label"></label>
                        <input asp-for="Word.AlternativeAnswer" class="form-control" />
                        <span asp-validation-for="Word.AlternativeAnswer" class="text-danger"></span>
                    </div>
                    <div class="form-group">
                        <label asp-for="Word.Hint" class="control-label"></label>
                        <input asp-for="Word.Hint" class="form-control" />
                        <span asp-validation-for="Word.Hint" class="text-danger"></span>
                    </div>
                    <div class="form-group">
                        <label asp-for="Word.Language" class="control-label"></label>
                        <input asp-for="Word.Language" class="form-control" />
                        <span asp-validation-for="Word.Language" class="text-danger"></span>
                    </div>
                    <div class="form-group">
                        <label asp-for="Word.Category" class="control-label"></label>
                        <input asp-for="Word.Category" class="form-control" />
                        <span asp-validation-for="Word.Category" class="text-danger"></span>
                    </div>
                    <div class="form-group">
                        <label asp-for="Word.Module" class="control-label"></label>
                        <input asp-for="Word.Module" class="form-control" />
                        <span asp-validation-for="Word.Module" class="text-danger"></span>
                    </div>
                    <div class="form-group">
                        <label asp-for="Word.Difficulty" class="control-label"></label>
                        <input asp-for="Word.Difficulty" class="form-control" />
                        <span asp-validation-for="Word.Difficulty" class="text-danger"></span>
                    </div>
                    <div class="form-group">
                        <label asp-for="WordUpload.SoundFile" class="control-label"></label>
                        <input asp-for="WordUpload.SoundFile" type="file" class="form-control" />
                        <span asp-validation-for="WordUpload.SoundFile" class="text-danger"></span>
                    </div>

                    <br>
                    <br>

                    <div class="form-group">
                        <input type="submit" value="Create" class="btn btn--blue" />
                    </div>
                </form>
            </div>
        </div>
    </div>
    <br>
    <br>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

WordUpload.SoundFile 未与模型一起传递。当我调试应用程序时,它在控制器/页面中返回为 null。所有其他属性都通过了,没有任何问题。

你知道如何传递文件吗?

【问题讨论】:

  • 查看File uploads in ASP.NET Core并注意enctype属性。
  • 发布表单时仍然显示 null 而不是文件。对于它发生的原因,您还有其他想法吗?
  • 您是否也考虑过使用一个模型类。将 IFormFile 属性合并到一个模型中,它应该可以工作。从文档中您还应该注意,您需要在表单中包含enctype="multipart/form-data"

标签: c# asp.net asp.net-core razor-pages


【解决方案1】:

您需要在表单中添加此内容:

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

在您的 post 方法中,如果您对模型绑定没有将文件绑定到您的模型有任何问题,您可以像这样直接从 Form.Files 获取它:

 var formFile = HttpContext.Request.Form.Files[0];

您应该首先检查 HttpContext.Request.Form.Files.Length 是否 > 0,否则该代码将引发错误。然后将字节复制到您的模型以保存。 另见documentation

【讨论】:

  • 我刚刚尝试将其添加到 from 但当我尝试发布表单时该属性仍然为空。对于可能导致它的原因,您还有其他想法吗?
  • @JoeAudette 我不认为你说的是​​真的,IFormFile 的模型绑定应该可以正常工作。我的猜测是 multipart/form-data 确实可以解决问题。
  • @HenkMollema 你是对的,文档看起来应该可以工作,但操作员说没有解决它。我将编辑我的答案,说如果您对文件模型绑定有任何问题,您可以直接从 Form.Files 获取它
  • 啊,我明白了,这很奇怪。感谢您的澄清。
猜你喜欢
  • 2020-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-17
  • 1970-01-01
  • 1970-01-01
  • 2019-06-25
  • 2021-07-06
相关资源
最近更新 更多