将 base64 字符串转换为 ArrayBuffer [英] Convert base64 string to ArrayBuffer

查看:66
本文介绍了将 base64 字符串转换为 ArrayBuffer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将 base64 编码字符串转换为 ArrayBuffer.base64 字符串是用户输入,它们将从电子邮件中复制和粘贴,因此在加载页面时它们不存在.如果可能,我想在不向服务器进行 ajax 调用的情况下在 javascript 中执行此操作.

I need to convert a base64 encode string into an ArrayBuffer. The base64 strings are user input, they will be copy and pasted from an email, so they're not there when the page is loaded. I would like to do this in javascript without making an ajax call to the server if possible.

我发现这些链接很有趣,但它们并没有帮助我:

I found those links interesting, but they didt'n help me:

ArrayBuffer 到 base64 编码字符串

这是相反的转换,从 ArrayBuffer 到 base64,而不是相反

this is about the opposite conversion, from ArrayBuffer to base64, not the other way round

http://jsperf.com/json-vs-base64/2

这看起来不错,但我不知道如何使用代码.

this looks good but i can't figure out how to use the code.

是否有一种简单的(可能是原生的)方法来进行转换?谢谢

Is there an easy (maybe native) way to do the conversion? thanks

推荐答案

试试这个:

function _base64ToArrayBuffer(base64) {
    var binary_string = window.atob(base64);
    var len = binary_string.length;
    var bytes = new Uint8Array(len);
    for (var i = 0; i < len; i++) {
        bytes[i] = binary_string.charCodeAt(i);
    }
    return bytes.buffer;
}

这篇关于将 base64 字符串转换为 ArrayBuffer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆