【问题标题】:How to convert byte[] in IFormFile in asp.net MVC Core?如何在 asp.net MVC Core 的 IFormFile 中转换字节 []?
【发布时间】:2018-11-14 21:48:43
【问题描述】:

我正在使用 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);
    }

【问题讨论】:

  • 您能否在您的问题GETPOST 中为您的控制器中的Edit 操作发布方法?
  • 当然,会相应地更新问题

标签: c# asp.net-mvc


【解决方案1】:

首先,我建议你使用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>
            }

【讨论】:

  • 我在显示图像时没有任何问题,问题是:我无法从字节数组转换为 FormFile
  • @Licentia 我今天遇到了同样的问题。有人解释说,您无法以编程方式设置 IFormFile,只有用户可以通过浏览器进行设置。您可以在这里阅读更多内容:stackoverflow.com/questions/53297803/…
猜你喜欢
  • 2020-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-12
  • 2020-10-27
  • 2017-10-23
  • 2023-02-02
  • 1970-01-01
相关资源
最近更新 更多