DOM异常5 javascript中有效base64图像字符串上的INVALID CHARACTER错误 [英] DOM Exception 5 INVALID CHARACTER error on valid base64 image string in javascript

查看:1313
本文介绍了DOM异常5 javascript中有效base64图像字符串上的INVALID CHARACTER错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将图像的base64字符串解码为二进制文件,以便可以通过操作系统在本地下载和显示。

I'm trying to decode a base64 string for an image back into binary so it can be downloaded and displayed locally by an OS.

我成功的字符串当使用数据URI前言(data:img / png; base64)作为HTML IMG元素的src时呈现,但是当使用atob函数或goog闭包函数时,它会失败。

The string I have successfully renders when put as the src of an HTML IMG element with the data URI preface (data: img/png;base64, ) but when using the atob function or a goog closure function it fails.

然而,当放入此处时解码成功: http://www.base64decode.org/

However decoding succeeds when put in here: http://www.base64decode.org/

任何想法?

编辑:
我成功地使用内置JS功能以外的其他库进行解码。但是,它仍然无法在本地打开 - 在Mac上说它已损坏或格式未知且无法打开。

I successfully got it to decode with another library other than the built-in JS function. But, it still won't open locally - on a Mac says it's damaged or in an unknown format and can't get opened.

代码如下:

imgEl.src = 'data:img/png;base64,' + contentStr; //this displays successfully
decodedStr = window.atob(contentStr); //this throws the invalid char exception but i just
//used a different script to get it decode successfully but still won't display locally

base64字符串本身太长而无法显示(限制为30,000个字符)

the base64 string itself is too long to display here (limit is 30,000 characters)

推荐答案

我只是把头撞在墙上一段时间。

I was just banging my head against the wall on this one for awhile.

这个问题有几种可能的原因。 1)Utf-8问题。这里有一个很好的写作+解决方案。 http://monsur.hossa.in/2012/07 /20/utf-8-in-javascript.html

There are a couple of possible causes to the problem. 1) Utf-8 problems. There's a good write up + a solution for that here. http://monsur.hossa.in/2012/07/20/utf-8-in-javascript.html

在我的情况下,我还必须确保所有的空格都在字符串之外将它传递给atob。例如

In my case, I also had to make sure all the whitespace was out of the string before passing it to atob. e.g.

function decodeFromBase64(input) {
  input = input.replace(/\s/g, '');
  return atob(input);
}

真正令人沮丧的是,使用python中的base64库正确解析了base64 ,但不是在JS。

What was really frustrating was that the base64 parsed correctly using the base64 library in python, but not in JS.

这篇关于DOM异常5 javascript中有效base64图像字符串上的INVALID CHARACTER错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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