将pdf作为base64字符串转换为字节数组时,输入不是有效的Base-64字符串

时间:2017-01-19 16:39:12

标签: javascript c#

使用Cordova Plugin FileReader转换pdf文件并将其发送到.Net服务器后,服务器抛出此错误“输入不是有效的Base-64字符串,因为它包含非基本64字符,超过两个填充字符,或填充字符中的非法字符。“将base64字符串转换为字节数组。

Java脚本代码:

window.resolveLocalFileSystemURL(data, 
function (fileEntry) {
    fileEntry.file(function (fileObj) {
        var reader = new FileReader();
        reader.onloadend = function (evt) {             
            base64StringDocument = evt.target.result;
        };
        reader.readAsDataURL(fileObj);    
    },
    function (error) {
        console.log('get fileEntry error: ' + error.message);
    });
},
function (error) {
  console.log('resolve error: ' + error.message);
});

C#代码:

int startIndexOfBase64 = base64String.IndexOf("base64,") + "base64,".Length;
base64String = base64String.Substring(startIndexOfBase64);

byte[] blob = Convert.FromBase64String(base64String);

Base64字符串开头:

  

数据:应用/ PDF; BASE64,JVBERi0xLjQKMSAwIG9iago8PCAvVHlwZSAvQ2F0YWxvZwovUGFnZXMgMiAwIFIKPj4KZW5kb2JqCjMgMCBvYmoKPDwgL1R5cGUgL1BhZ2UKL1BhcmVudCAyIDAgUgovUmVzb3VyY2VzIDQgMCBSCi9NZWRpYUJveCBbMCAwIDU5NSA4NDJdCi9Db250ZW50cyA1IDAgUgo + PgplbmRvYmoKNCAwIG9iago8PCAvUHJvY1NldCBbL1BERiAvSW

Base64字符串结束:

  

wMDIyOTI1NiAwMDAwMCBuDQowMDAwMjI5MzYxIDAwMDAwIG4NCjAwMDAyMjk0MzMgMDAwMDAgbg0KMDAwMDIyOTU5MiAwMDAwMCBuDQowMDAwNDU1MDkwIDAwMDAwIG4NCnRyYWlsZXIKPDwgL1NpemUgMTMKL1Jvb3QgMSAwIFIKPj4Kc3RhcnR4cmVmCjQ1NTE3NwolJUVPRg ==

1 个答案:

答案 0 :(得分:1)

非常感谢您的评论,但在base64上应用以下正则表达式解决了这个问题。

var btn = $("input[name=submitname]");
            var url = btn.parents("form").attr("action");
                var fileName = btn.parents("form").find("input[type=file]").attr("name");
                var fileVal = btn.parents("form").find("input[type=file]").val();
            var dataString = btn.parents("form").serialize() + "&" + btn.attr("name") + "=" + btn.val() + "&" + fileName + "=" + fileVal;
                $.ajax({
                    url: url,
                    type: "POST", 
                    data: dataString, 
                    processData: false,
                    contentType: false,
                    cache: false,
                    success: function(data){
                        console.log(data);
                    }, error: function(errData){
                        console.log(url);
                        console.log(dataString);
                        console.log("error:");
                        console.log(errData);
                    }
                });