繁体   English   中英

使用JavaScript将文件从Base 64转换为Base 64并使用C#将其转换回文件

[英]Convert a file from to Base 64 using JavaScript and converting it back to file using C#

我正在尝试使用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. "}

请告诉我如何继续这个...谢谢

根据MDN:FileReader.readAsDataURL,这些生成的URL的前缀是data:image/jpeg;base64, . 看看你生成的字符串。 查找base64,并获取在此前缀后面开始的base64数据。

因为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));    

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM