在ASP.NET Core 2剃刀页面中上传文件

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

我正在尝试在asp.net core 2 razor页面上进行简单的文件上传。我有下面的代码。请意识到它是不完整的。当我在我的VS2017中运行时,我检查了我的FileUpload对象,遗憾的是它是null。我希望它是除null之外的东西,我可以创建一个流来从中获取一些数据。但是,如果对象为null,我会怀疑我没有正确绑定的东西。任何想法都表示赞赏。谢谢。

cs背后的代码:

public class PicturesModel : PageModel
{
    public PicturesModel()
    {

    }
    [Required]
    [Display(Name = "Picture")]
    [BindProperty]
    public IFormFile FileUpload { get; set; }

    public async Task OnGetAsync()
    {

    }

    public async Task<IActionResult> OnPostAsync()
    {
        //FileUpload is null
        return RedirectToPage("/Account/Pictures");
    }
}

前端cshtml文件;

<form method="post" enctype="multipart/form-data">
    <label asp-for="FileUpload"></label>
    <input type="file" asp-for="FileUpload" id="file" name="file" />
    <input type="submit" value="Upload" />
</form>
c# asp.net razor asp.net-core-2.0
3个回答
2
投票

您的文件输入属性名为FileUpload,但您已覆盖TagHelper生成的name属性,并将其重命名为与属性名称不匹配的file

将视图代码更改为

<input type="file" asp-for="FileUpload" />

这样它就会生成正确的name属性(这是name="FileUpload")。还要注意删除id="file",这意味着你点击时<label>不会将焦点设置到相关控件上。


0
投票

Post方法中没有files参数。

在这里查看教程:https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads


0
投票

今天早上我花了很多时间尝试各种解决方案,但似乎都没有。但最终,我想出了这个......享受。

    /// <summary>
    /// Upload a .pdf file for a particular [User] record
    /// </summary>
    [AllowAnonymous]
    [HttpPost("uploadPDF/{UserId}")]
    public async Task<IActionResult> uploadPDF(string UserId, IFormFile inputFile)
    {
        try
        {
            if (string.IsNullOrEmpty(UserId))
                throw new Exception("uploadPDF service was called with a blank ID.");
            Guid id;
            if (!Guid.TryParse(RequestId, out id))
                throw new Exception("uploadPDF service was called with a non-GUID ID.");

            var UserRecord = dbContext.Users.FirstOrDefault(s => s.UserID == id);
            if (UserRecord == null)
                throw new Exception("User record not found.");

            var UploadedFileSize = Request.ContentLength;
            if (UploadedFileSize == 0)
                throw new Exception("No binary data received.");

            var values = Request.ReadFormAsync();
            IFormFileCollection files = values.Result.Files;
            if (files.Count == 0)
                throw new Exception("No files were read in.");

            IFormFile file = files.First();
            using (Stream stream = file.OpenReadStream())
            {
                BinaryReader reader = new BinaryReader(stream);
                byte[] bytes = reader.ReadBytes((int)UploadedFileSize);

                Trace.WriteLine("Saving PDF file data to database..");
                UserRecord.RawData = bytes;
                UserRecord.UpdatedOn = DateTime.UtcNow;
                dbContextWebMgt.SaveChanges();
            }

            return new OkResult();
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "uploadPDF failed");
            return new BadRequestResult();
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.