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

C# MVC Core中通过Blob为file输入框填充数据库动物图片报错求助

修复ASP.NET Core MVC中Blob填充input[type="file"]的问题

问题场景

开发动物对象数据编辑页面时,需要将数据库中存储的byte[]格式动物图片,通过Blob填充到input[type="file"]标签中,现有JavaScript代码执行后浏览器报错,无法实现预期效果。

现有代码

Animal类代码

public class Animal
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string Sex { get; set; }
    public int Age { get; set; }
    public string Breed { get; set; }
    public DateTime DateOfPost { get; set; }
    public Guid UserId { get; set; }
    public byte[] ImageData { get; set; }
    public string FileName { get; set; }
    public string ContentType { get; set; }
    public virtual User User { get; set; }
}

视图中的JavaScript代码

<script>
    const blob = new Blob([@Animal.ImageData], { type: '@Animal.ContentType' });

    const file = new File([blob], '@Animal.FileName', { type: '@Animal.ContentType ' });

document.querySelector('input[type="file"]').files = file;
</script>

错误原因

  1. byte[]输出格式错误:直接在JS中输出@Animal.ImageData,会得到类似System.Byte[]或者逗号分隔的数字字符串,并非JavaScript可识别的字节数组,无法正确构造Blob。
  2. File对象赋值方式错误:input的files属性是只读的FileList类型,不能直接赋值单个File对象,必须通过合法方式构造FileList后再赋值。

修复方案

步骤1:后端将byte[]转换为Base64字符串

在Controller中获取Animal对象后,将ImageData转换为Base64格式,传递到视图:

// 示例:在编辑页面的Action中
public IActionResult Edit(Guid id)
{
    var animal = _animalService.GetById(id);
    // 将byte[]转为Base64字符串
    ViewBag.ImageBase64 = animal.ImageData != null ? Convert.ToBase64String(animal.ImageData) : null;
    return View(animal);
}

步骤2:前端修改JavaScript代码

通过Base64字符串构造Blob,再构造合法的FileList赋值给input:

<script>
// 工具函数:将Base64字符串转为Blob
function base64ToBlob(base64, contentType) {
    const byteCharacters = atob(base64);
    const byteArrays = [];
    for (let offset = 0; offset < byteCharacters.length; offset += 512) {
        const slice = byteCharacters.slice(offset, offset + 512);
        const byteNumbers = new Array(slice.length);
        for (let i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
        }
        const byteArray = new Uint8Array(byteNumbers);
        byteArrays.push(byteArray);
    }
    return new Blob(byteArrays, { type: contentType });
}

// 获取视图传递的图片数据
const base64Data = '@ViewBag.ImageBase64';
const contentType = '@Model.ContentType';
const fileName = '@Model.FileName';

// 仅当存在图片数据时执行填充
if (base64Data) {
    const blob = base64ToBlob(base64Data, contentType);
    const file = new File([blob], fileName, { type: contentType });
    
    // 构造FileList对象
    const dataTransfer = new DataTransfer();
    dataTransfer.items.add(file);
    // 赋值给input的files属性
    document.querySelector('input[type="file"]').files = dataTransfer.files;
}
</script>

注意事项

  • 若ImageData可能为null,需添加非空判断,避免前端执行报错。
  • 确保ContentType的值合法(如image/jpeg、image/png),否则Blob无法正确识别图片类型。
  • 后端转换Base64时不要添加data:image/xxx;base64,前缀,前端会自行指定contentType。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 03:10:16