C# 是否将base64字符串转换图像附加到后端的请求表单数据?

C# 是否将base64字符串转换图像附加到后端的请求表单数据?,c#,.net,.net-core,C#,.net,.net Core,因此,我有一个base64字符串,它将被传递到一个端点,在该端点中,我需要将其转换为一个图像,然后将其附加到表单数据中。可能吗 现在我有这样的东西 Image img = options.base64String.ToImage(); 我希望图像附在请求的表单数据中,这样我就可以像这样得到它: Image img = options.base64String.ToImage(); Request.Form.Files.Add(img); // I want to add the image

因此,我有一个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;
public class InputModel
{
    // actual image
    public byte[] ProfilePic { get; set; }

    // image to pass to POST method (so to update)
    public IFormFile ProfilePicToUpdate { get; set; }
}
<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>
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}'.");
                }
            }
        }
    }

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

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


谢谢

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

我将图像以
字节[]
的形式存储在数据库中,因此使用字节数组并显示来自此字节数组的图像,但使用
IFormFile
对象对其进行更新

例如,我有一个用户模型,它存储在数据库中,具有
ProfilePic
属性,但也有另一个模型(
视图模型
)用于更新它

我的模型到数据库:

class UserModel
{
    public byte[] ProfilePic{get;set;}
}
我的
ViewModel
显示或更新用户的个人资料图片如下:

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;
public class InputModel
{
    // actual image
    public byte[] ProfilePic { get; set; }

    // image to pass to POST method (so to update)
    public IFormFile ProfilePicToUpdate { get; set; }
}
<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>
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}'.");
                }
            }
        }
    }

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

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();
}
公共异步任务OnGetAsync() { var user=await\u userManager.GetUserAsync(用户); if(user==null) { 抛出新的ApplicationException($“无法加载ID为“{{u userManager.GetUserId(user)}”的用户”); } 输入=新输入模型 { ProfilePic=user.ProfilePic, XP=user.XP, 地址=用户地址, BirthDate=user.BirthDate }; 返回页(); } 在页面上显示个人资料图片,如下所示:

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;
public class InputModel
{
    // actual image
    public byte[] ProfilePic { get; set; }

    // image to pass to POST method (so to update)
    public IFormFile ProfilePicToUpdate { get; set; }
}
<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>
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}'.");
                }
            }
        }
    }

}

侧面图
@if(Model.Input.ProfilePic!=null)
{
}
其他的
{
}
拯救
并按如下方式在Post方法中处理图像:

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;
public class InputModel
{
    // actual image
    public byte[] ProfilePic { get; set; }

    // image to pass to POST method (so to update)
    public IFormFile ProfilePicToUpdate { get; set; }
}
<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>
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}'.");
                }
            }
        }
    }

}
公共异步任务OnPostAsync(IFormFile=null) { 如果(!ModelState.IsValid) { 返回页(); } if(Input.profilePictupDate!=null&&Input.profilePictupDate.Length>0) { 使用(var memoryStream=new memoryStream()) { 等待输入.profilePictupDate.CopyToAsync(memoryStream); var profilePicBytes=memoryStream.ToArray(); if(user.ProfilePic==null | |!profilePicBytes.SequenceEqual(user.ProfilePic)) { user.ProfilePic=memoryStream.ToArray(); var setProfilePic=wait_userManager.UpdateAsync(用户); 如果(!setProfilePic.successed) { 抛出新的ApplicationException($“为ID为“{user.ID}”的用户设置配置文件图片时发生意外错误”; } } } } }
无法修改
HttpRequest
对象;它在整个请求期间是不可变的。这包括
HttpRequest.Form.Files

您可以影响处理请求输入流数据的方式。由于输入流包含表单字段,因此可以使用过滤器修改请求中的表单数据。但是,它确实有一些警告:

  • 这只在请求管道的早期起作用。一旦管道中的任何内容与输入流交互(包括从
    表单
    中读取任何内容),就太晚了
  • 您正在使用原始数据流。没有
    Form[“Hello”]
    在这里起作用-您需要了解HTTP表单的编码方式,精确解析数据,并动态重新创建正确的更改表单数据
除非你真的别无选择,否则我建议你避免这样做


一个相对简单的替代方法是使用实际的请求数据创建一个新的web请求,并从中返回结果(确保您发出的请求不会导致另一个请求,否则可能会导致无限循环阻塞您的服务:)。当然,你需要确保你提出的新请求包含所有正确的数据;没有简单的方法可以将
HttpRequest
转换为一个新的
HttpWebRequest

非常感谢您的回复,但我认为我不太明白这个例子。另外,请注意,我只能访问应用程序的API,因此我无法真正修改前端。我更新了问题以获得更多澄清。您是否正在尝试创建对某个第三方API的新请求?看起来您正试图修改当前的请求对象,这是完全不同的。