【问题标题】:Convert a file from to Base 64 using JavaScript and converting it back to file using C#使用 JavaScript 将文件从 Base 64 转换为使用 C# 的文件
【发布时间】:2018-03-25 23:24:27
【问题描述】:

我正在尝试使用 javascript 将 pdf 和图像文件转换为 base 64,并使用 WEB API 中的 C# 将其转换回文件。

Javascript

var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0)
{
    var fileToLoad = filesSelected[0];
    var fileReader = new FileReader();
    fileReader.onload = function(fileLoadedEvent) 
    {
        var textAreaFileContents = document.getElementById("textAreaFileContents");
        textAreaFileContents.innerHTML = fileLoadedEvent.target.result;
    };
    fileReader.readAsDataURL(fileToLoad);
}

C#

Byte[] bytes = Convert.FromBase64String(dd[0].Image_base64Url);
File.WriteAllBytes(actualSavePath,bytes);

但在 API 中,我遇到了 {"The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters. "} 的异常

请告诉我如何进行此操作... 谢谢

【问题讨论】:

  • 你发布的 api 是什么?应该是fileReader.result
  • 是的,我正在发布 fileReader.result...
  • 你能发布控制器 api 动作吗?发布为 dd[0].Image_base64Url 的值是多少

标签: javascript c# asp.net-web-api


【解决方案1】:

根据MDN: FileReader.readAsDataURL,这些生成的 URL 都带有 data:image/jpeg;base64, 之类的前缀。看看你生成的字符串。查找base64, 的出现,并取此前缀之后开始的base64 数据。

【讨论】:

  • 删除数据:image/jpeg;base64,工作。如果有人遇到同样的问题,请使用此脚本从 URL 中删除前缀... var base64result = reader.result.split(',')[1];
  • 在尝试上传更大的文件时,比如说 5MB,脚本运行时没有将文件转换为字节。导致 API 出现空错误...对此有什么解决办法吗??
  • @Hem 我已经使用 MDN 实时结果将 11mb 图像转换为 base64 字符串,从 firefox 中提取生成的 url,将数据转储到文件中,在 C# 中读取此文件以进行解码base64数据并写出图像。这样可行。所以它可能是浏览器依赖设置或插件或类似的东西。您所说的“无需转换即可运行”是什么意思? load 事件是否被触发? FileReader 也有一个 progress 和一个 error 事件...
【解决方案2】:

因为FileReader.readAsDataURL() 会生成一个以额外元数据(“URL”部分)为前缀的字符串,所以您需要在 C# 端将其去掉。下面是一些示例代码:

// Sample string from FileReader.readAsDataURL()
var base64 = "data:image/jpeg;base64,ba9867b6a86ba86b6a6ab6abaa====";

// Some known piece of information that will be in the above string
const string identifier = ";base64,";

// Find where it exists in the input string
var dataIndex = base64.IndexOf(identifier);

// Take the portion after this identifier; that's the real base-64 portion
var cleaned = base64.Substring(dataIndex + identifier.Length);

// Get the bytes
var bytes = Convert.FromBase64String(cleaned);

如果太冗长可以精简一下,我只是想一步一步解释。

var bytes = Convert.FromBase64String(base64.Substring(base64.IndexOf(";base64,") + 8));    

【讨论】:

    猜你喜欢
    • 2020-10-16
    • 2013-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-19
    • 2010-10-18
    相关资源
    最近更新 更多