c# - 如何在 ASP.Net Core 2.0 Razor 页面中发布 IFormFile?

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

我正在使用 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");
    }
}

和 View - 页面:
@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 不与模型一起传递。当我调试应用程序时,它在 Controller /页面中返回为 null。所有其他属性都通过,没有任何问题。

你知道如何传递文件吗?

最佳答案

你需要在你的表单上添加这个:

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

在您的 post 方法中,如果您在模型绑定(bind)没有将文件绑定(bind)到模型时遇到任何问题,您可以直接从 Form.Files 获取它,如下所示:
 var formFile = HttpContext.Request.Form.Files[0];

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

关于c# - 如何在 ASP.Net Core 2.0 Razor 页面中发布 IFormFile?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50861800/

相关文章:

c# - 如何获取 7-zip 存档中打包文件的大小

c# - Visual Studio + 单声道 : 'Gtk' could not be found

c# - App_Code 和服务器

c# - JsonProperty c# 将字典值序列化为数组

c# - 从 C# 中的字符串中提取 5 位数字的最快方法是什么

c# - 向 SQL Express 表添加全文搜索

asp.net - 嘶嘶声选择器引擎错误

c# - 在 ASP.NET MVC 中通过 jQuery 提交表单时传递参数

c# - 在 Mac 上从命令行运行 ASP.NET 5 应用程序时是否使用 launchSettings.json?

c# - 如何配置 Startup 类构造函数可用的 DI 服务