繁体   English   中英

如何在asp.net MVC Core的IFormFile中转换byte []?

[英]How to convert byte[] in IFormFile in asp.net MVC Core?

我正在使用IFormFile添加图像,然后将文件转换为字节数组并将其保存到我的数据库中,而不是能够读取图像并显示它。

但是,从视图的角度来看,在编辑模式下打开保存的记录时,我在其中添加图像,因此看不到以前保存的图像。

所以在视图上我有以下代码:

<input type="file" asp-for="BAN_IMAGE_FILE">

在我的模型上,我具有以下属性

    public byte[] BAN_IMAGE {get;set;}

    private IFormFile _BAN_IMAGE_FILE;

    [NotMapped]
    public IFormFile BAN_IMAGE_FILE
    {
        get => _BAN_IMAGE_FILE;
        set
        {
            _BAN_IMAGE_FILE = value;

            if (_BAN_IMAGE_FILE != null)
            {
                using (var ms = new MemoryStream())
                {
                    _BAN_IMAGE_FILE.CopyTo(ms);
                    var fileBytes = ms.ToArray();
                    BAN_IMAGE = fileBytes;
                }
            }

        }
    }

因此,如您所见,选择文件后,我将执行的操作将其转换为字节数组,因此当我单击“保存”按钮时,数据将被保存。

我想要做的是,当我单击“编辑”时,我想要获取字节数组并将其转换为FormFile,以便在屏幕上显示它,有什么建议怎么做?

控制器中的编辑方法:

public async Task<IActionResult> Edit(int? id)
    {
        if (User.Identity.IsAuthenticated != true)
            return NotFound();

        if (id == null)
        {
            return NotFound();
        }

        var tEvents = await _context.TEVENTS.Include(x => x.BANNERS).Include(x=>x.PHOTO_GALLERY).Include(x=>x.EVENT_TYPES)
            .FirstOrDefaultAsync(x => x.TE_ROWID.Equals(id));

        ViewBag.EvenTypes = GetEventTypes();

        if (tEvents == null)
        {
            return NotFound();
        }
        return View(tEvents);
    }

首先,我建议您对IFormFile类型使用viewmodel,就像它写在>> DOCUMENTATION <<中

另一件事,我不知道带有保存图像的视图文件的外观,但是要获得图像,您应该使用类似以下内容的图像:

@model YourViewModel
(...)
@if (item.AktualnosciImage != null)
            {
//if the file exists in database
                <div style="background-image: url(data:image;base64,@System.Convert.ToBase64String(item.YourViewModelsImageProperty))"></div>
            }
            @if (item.AktualnosciImage == null)
            {

//if the file does not exists in database
                <div style="background-image: url(/img/Aktualnosci/default.jpg)"></div>
            }

暂无
暂无

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

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