如何在 ASP.NET Core Web API 和 C# 中将 Base64 字符串转换为 IForm 文件?

问题描述 投票:0回答:1

我想使用 ASP.NET Core Web API 项目将前端文件的请求作为 Base64 字符串格式传递。在我想将该 Base64 字符串请求转换为

IForm
文件之后。

只有这样改变我才能保存:

    // Demo model class
    public class CreatePost
    {
       public string Type { set;get; }
       public IFormFile MyImage { set; get; }
    }

    // controller action method 
    public async Task<IActionResult>UploadFile(string base64String)
    {
        CreatePost() createPost = new CreatePost();
        // how to convert here Base64 string to IForm file.
    }
c# file-io asp.net-core-webapi
1个回答
0
投票

您的问题看起来像是由您面临的其他问题引起的。我强烈建议直接接受控制器中的

IFormFile
并要求您的 Web 应用程序或 Web API 客户端以原始格式向您发送文件。 Base64 可能是一个不错的选择,但不适用于大文件。如果您不小心处理非常大的文件,它们会耗尽您的内存和处理时间。文件扩展名和文件名怎么样?您还必须将其添加到模型中。离重新发明轮子越来越近了。当您可以简单地通过框架完成它并将文件作为
IFormFile
放在盘子上交付给您时,为什么要付出额外的努力?

但无论如何,从相对较小的 Base64 字符串创建

FormFile
非常简单:

public FormFile CreateFormFileFromBase64(string base64File)
{
    var stream = new MemoryStream();
    var bytes = Convert.FromBase64String(base64File);

    stream.Write(bytes);
    stream.Position = 0;

    return new FormFile(stream, 0, stream.Length, "file", "file-name");
}

要处理较大的文件,请使用某种缓冲或

CryptoStream
进行适当的转换。

© www.soinside.com 2019 - 2024. All rights reserved.