doutong7216 2014-06-06 03:52
浏览 97
已采纳

如何使用具有浏览器兼容性的jquery获取base64字符串文件上传?

hi I can anyone help me I need to get just the base_64 code of the csv file I want to upload

this is my code with filter of csv

function readCSV(input) {
    if (input.files && input.files[0]) {

        var filename = input.files[0].name;
        var ext = filename.split('.').pop();

        if(input.files[0].type == "text/csv" || ext == "csv" || ext == "xls"){
            var reader = new FileReader();

            reader.onload = function (e) {
            var base_64 = e.target.result;
            console.log(base_64);

            var array = new Uint8Array(100);
                array[42] = 10;
                $('#file_name').html(input.files[0].name);
                $('#filename').val(input.files[0].name);
                $('#content').val(base_64);

            }
            reader.readAsDataURL(input.files[0]);
        }else{
            $('#file_name').html('<span style="color:red; font-size:11px"><i class="fa fa-ban"></i> Invalid File Please try again!</span>');
        }
    }
}

in my logcat when I console.log(base_64)

the result from Google Chrome was

data:base64,UHJvZHVjdCBOYW1lL....(rest of base_64 string)

I just need to have the base_64 string

so I came out with this solution

//replace function content.replace('data:;base64,', '');

i just remove the data:base64, in the string

but when i tried in firefox the result was

data:application/octet-stream;base64,UHJvZHVjdCBOYW1lL....(rest of base_64 string)

differ from the first result so my replace function won't work

but I don't want to add another replace function because my worries is if browser push an update maybe the data:base64 will be 1.0.data:base64 or v.1.data:base64 so whenever the string changes my system will fail.

could anyone help me please. I just need to get the base_64 string, Thanks in advance.

  • 写回答

2条回答 默认 最新

  • douzhuiqing1151 2014-06-06 04:07
    关注

    I would split the string using a comma as a delimiter, and then grab the last element from the newly created array which will represent your base64 data:

    //split into ['data:application/octet-stream;base64', 'UHJvZHVjdCBOYW1lL']
    var arr = content.split(',');
    var base64 = arr[arr.length-1];
    

    As mentioned by bergi, the base64 data is defined to appear after the last comma

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?