简体   繁体   中英

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.

<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 :

[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.

Ref: Uploading Files in Razor Pages

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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