你怎么能带code字符串为Base64在JavaScript中? [英] How can you encode a string to Base64 in JavaScript?

查看:148
本文介绍了你怎么能带code字符串为Base64在JavaScript中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个PHP脚本,可以连接code PNG图像到Ba​​se64字符串。

I have a PHP script that can encode a PNG image to a Base64 string.

我想这样做使用JavaScript同样的事情。我知道如何打开文件,但我不知道该怎么办编码?我不习惯用二进制数据。

I'd like to do the same thing using JavaScript. I know how to open files, but I'm not sure how to do the encoding? I'm not used to working with binary data.

推荐答案

如果你正在写code,这并不需要支持IE9或更早版本,那么你可以使用的 BTOA() 和的 ATOB() 转换和从base64编码。否则,使用类似<一个href=\"http://stackoverflow.com/questions/246801/how-can-you-en$c$c-to-base64-using-javascript#246813\">the阳光运作参考。

If you’re writing code that doesn’t need to support IE9 or earlier, then you can use btoa() and atob() to convert to and from base64 encoding. Otherwise, use something like the function Sunny referenced.

有似乎是在评论有关是什么这些函数接受/回报有些混乱,所以...

There appears to be some confusion in the comments regarding what these functions accept/return, so…


  • BTOA()接受串,其中的每个字符重新presents 8位字节 - 如果你传递一个包含字符,可以字符串'T重新在8位psented $ p $,它会可能打破。这不是的如果的你实际上是对待字符串作为一个字节数组的一个问题,但如果你想做些别的事情,那么你就必须设有code首次。

  • btoa() accepts a "string" where each character represents an 8-bit byte – if you pass a string containing characters that can’t be represented in 8 bits, it will probably break. This isn’t a problem if you’re actually treating the string as a byte array, but if you’re trying to do something else then you’ll have to encode it first.

ATOB()返回字符串,其中的每个字符重新presents一个8位字节 - 也就是说,它的价值将介于 0 0xFF的。这确实的的意思是ASCII - presumably如果你使用这个功能在所有的,你还指望用二进制数据和合作而不是文本

atob() returns a "string" where each character represents an 8-bit byte – that is, its value will be between 0 and 0xff. This does not mean it’s ASCII – presumably if you’re using this function at all, you expect to be working with binary data and not text.

  • How do I load binary image data using Javascript and XMLHttpRequest?

这篇关于你怎么能带code字符串为Base64在JavaScript中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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