【问题标题】:HttpPostedFileBase always get null in MVC Razor pagesHttpPostedFileBase 在 MVC Razor 页面中总是为空
【发布时间】:2020-05-07 18:31:19
【问题描述】:

我创建了一种表单,用户可以在其中上传个人资料照片,并将其以字节数组的形式存储在数据库中。 但在 post 方法中,我得到 HttpPostedFileBase 属性的值为 null。

<form id="profile-form" method="post" enctype="multipart/form-data">
    <div class="col-md-6">
       <div class="row">
            <div class="form-group col-md-6">
                 <img id="output" style="height:200px; width:200px;" />
            </div>
       </div>
       <div class="row">
            <div class="form-group col-md-12">
                <input asp-for="Input.ProfilePhoto" type="file" onchange="loadFile(event)" class="form-control">
            </div>
       </div>
       <button type="submit" class="btn btn-default" value="Upload">Save</button>
   </div>
</form>

public class Input
{
      [Display(Name = "Profile Photo")]
      public HttpPostedFileBase ProfilePhoto { get; set; }
}

public async Task<IActionResult> OnPostAsync()
{

}

【问题讨论】:

  • 您确定在表单中添加了 enctype="multipart/form-data" 吗?
  • 我已经添加了&lt;form id="profile-form" method="post" enctype="multipart/form-data"&gt;
  • 然后更改 HttpPostedFileBased -> IFormFile

标签: c# asp.net-mvc image razor-pages httppostedfilebase


【解决方案1】:

等效于HttpPosteFileBase 的ASP.NET Core 是IFormFile

[BindProperty]
public IFormFile Upload { get; set; }

public async Task OnPostAsync()
{
    var file = Path.Combine(_environment.ContentRootPath, "uploads", Upload.FileName);
    using (var fileStream = new FileStream(file, FileMode.Create))
    {
        await Upload.CopyToAsync(fileStream);
    }
}

您还需要使用[BindProperty] 属性来装饰IFormFile 属性(或它所在的类)。

参考:Uploading Files in Razor Pages

【讨论】:

    猜你喜欢
    • 2016-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-17
    • 2012-01-23
    • 1970-01-01
    • 1970-01-01
    • 2014-06-29
    相关资源
    最近更新 更多