You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Razor视图上传文件绑定byte[]类型属性时接收值为null如何解决

问题原因
  • 表单默认编码格式不支持文件传输,你没有给form标签添加enctype="multipart/form-data"属性
  • ASP.NET Core默认模型绑定无法直接将上传的文件流映射到模型的byte[]类型属性,上传的文件默认会被绑定为IFormFile类型
解决步骤

1. 修改前端表单代码

给form标签新增文件上传所需的编码属性,同时明确文件输入框的type属性:

<!-- 新增enctype属性 -->
<form asp-action="UploadImage" asp-controller="Categories" method="post" enctype="multipart/form-data">
    <div>
        <label asp-for="Picture"></label>
        <span asp-validation-for="Picture"></span><br/>
        <img src='@Url.Action("GetCategoryImage", "Categories", new { id = Model.CategoryId })' /><br/>
        <!-- 明确type为file,name和后端接收参数对应 -->
        <input type="file" name="picture" />
    </div>
    <br/>
    <div class="form-group">
        <input asp-for="CategoryId" type="hidden" />
        <input type="submit" name="save" class="btn btn-primary" value="Upload" />
    </div>
</form>

2. 修改后端控制器逻辑

在Action中单独接收上传的IFormFile对象,手动转换为byte[]后赋值给实体属性:

public async Task<IActionResult> UploadImage(Category category, IFormFile picture)
{
    // 把上传的文件转成byte数组
    if (picture != null && picture.Length > 0)
    {
        using var memoryStream = new MemoryStream();
        await picture.CopyToAsync(memoryStream);
        category.Picture = memoryStream.ToArray();
    }

    _db.Get(category.CategoryId).Picture = category.Picture;
    await _db.SaveChangesAsync().ConfigureAwait(false);

    return Redirect("Index");
}
可选优化方案

如果希望保持绑定逻辑更规范,可以新增专门的上传视图模型,前端直接绑定到该视图模型的属性即可,不需要手动修改input的name属性:

public class CategoryImageUploadViewModel
{
    public int CategoryId { get; set; }
    public IFormFile Picture { get; set; }
}

内容的提问来源于stack exchange,提问作者Chmelya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 05:24:03