简体   繁体   English

HttpPostedFileBase 在 MVC Razor 页面中始终为 null

[英]HttpPostedFileBase always get null in MVC Razor pages

I have created one form where user can upload profile photo, and it stores in database as byte array.我创建了一种用户可以上传个人资料照片的表单,并将其作为字节数组存储在数据库中。 but in post method i'm getting the value of HttpPostedFileBase property is null.但在 post 方法中,我得到HttpPostedFileBase属性的值为空。

<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()
{

}

The ASP.NET Core equivalent to HttpPosteFileBase is IFormFile :相当于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);
    }
}

You also need to decorate the IFormFile property (or the class that it is in) with the [BindProperty] attribute.您还需要使用[BindProperty]属性修饰IFormFile属性(或它所在的类)。

Ref: Uploading Files in Razor Pages参考: 在 Razor 页面中上传文件

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

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