首页 > 解决方案 > 附加base64字符串转换的图像以请求后端的表单数据?

问题描述

所以我有一个 base64 字符串,它将被传递到一个端点,在该端点中我需要将其转换为图像,然后将其附加到表单数据中。那可能吗?

现在我有这样的东西

Image img = options.base64String.ToImage();

我希望将图像附加到请求的表单数据中,这样我就可以得到它:

Image img = options.base64String.ToImage();

Request.Form.Files.Add(img); // I want to add the image on something like this

var files = Request.Form.Files;

我想将 img 附加到Request.Form.Files

另请注意,我只能访问应用程序的 API。

谢谢!

标签: c#.net.net-core

解决方案


当然这是可能的。我有一个解决方案,我还在我的ASP.NET Web App中使用图像。

我将图像存储在数据库byte[],因此是一个字节数组并显示来自该字节数组的图像,但用一个IFormFile对象更新它。

例如,我有一个存储在数据库中的用户模型,该模型具有属性但也有另一个模型()来更新它。ProfilePicViewModel

我的数据库模型:

class UserModel
{
    public byte[] ProfilePic{get;set;}
}

ViewModel要显示或更新用户的个人资料图片是这样的:

public class InputModel
{
    // actual image
    public byte[] ProfilePic { get; set; }

    // image to pass to POST method (so to update)
    public IFormFile ProfilePicToUpdate { get; set; }
}

当页面显示时,我从数据库中填充我的个人资料图片数组

public async Task<IActionResult> OnGetAsync()
{
    var user = await _userManager.GetUserAsync(User);
    if (user == null)
    {
        throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
    }

    Input = new InputModel
    {
        ProfilePic = user.ProfilePic,
        XP = user.XP,
        Address = user.Address,
        BirthDate = user.BirthDate
    };
    return Page();
}

在页面上显示个人资料图片,如下所示:

<form method="post" enctype="multipart/form-data">
    <h4>Profile picture</h4>
    @if (Model.Input.ProfilePic != null)
    {
        <object class="" data="data:image/png;base64,@Convert.ToBase64String(Model.Input.ProfilePic)" width="224" height="224" type="image/png"></object>
    }
    else
    {
        <img class="" src="~/images/profilePicDefault50x50.png" width="224" height="224" />
    }
    <input asp-for="Input.ProfilePicToUpdate" class="form-control" />
    <span asp-validation-for="Input.ProfilePicToUpdate" class="text-danger"></span>
    <button type="submit" class="btn btn-default">Save</button>
</form>

并像这样在 Post 方法中处理图像:

public async Task<IActionResult> OnPostAsync(IFormFile file = null)
{
    if (!ModelState.IsValid)
    {
        return Page();
    }
    if(Input.ProfilePicToUpdate != null && Input.ProfilePicToUpdate.Length > 0)
    {
        using (var memoryStream = new MemoryStream())
        {
            await Input.ProfilePicToUpdate.CopyToAsync(memoryStream);
            var profilePicBytes = memoryStream.ToArray();

            if(user.ProfilePic == null || !profilePicBytes.SequenceEqual(user.ProfilePic))
            {
                user.ProfilePic = memoryStream.ToArray();
                var setProfilePic = await _userManager.UpdateAsync(user);
                if (!setProfilePic.Succeeded)
                {
                    throw new ApplicationException($"Unexpected error occurred setting profile picture for user with ID '{user.Id}'.");
                }
            }
        }
    }

}

推荐阅读