如何解析Node中的数据URL?

时间:2021-06-11 20:44:19

I've got a data URL like this:

我有一个这样的数据网址:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...

What's the easiest way to get this as binary data (say, a Buffer) so I can write it to a file?

最简单的方法是将它作为二进制数据(例如,缓冲区),以便将其写入文件?

3 个解决方案

#1


54  

Put the data into a Buffer using the 'base64' encoding, then write this to a file:

使用'base64'编码将数据放入Buffer中,然后将其写入文件:

var fs = require('fs');
var string = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
var regex = /^data:.+\/(.+);base64,(.*)$/;

var matches = string.match(regex);
var ext = matches[1];
var data = matches[2];
var buffer = new Buffer(data, 'base64');
fs.writeFileSync('data.' + ext, buffer);

#2


20  

Try this

尝试这个

var dataUrl = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
var buffer = new Buffer(dataUrl.split(",")[1], 'base64');

#3


3  

I also met such questions (parsing and validating data URL) recently and found the following workaround: https://gist.github.com/bgrins/6194623

我最近也遇到了这样的问题(解析和验证数据URL)并找到了以下解决方法:https://gist.github.com/bgrins/6194623

I created 2 packages to make working with data URL easier in the code. Here they are: https://github.com/killmenot/valid-data-url
https://github.com/killmenot/parse-data-url

我创建了2个包,以便在代码中更轻松地处理数据URL。它们是:https://github.com/killmenot/valid-data-url https://github.com/killmenot/parse-data-url

Check out examples

查看示例

#1


54  

Put the data into a Buffer using the 'base64' encoding, then write this to a file:

使用'base64'编码将数据放入Buffer中,然后将其写入文件:

var fs = require('fs');
var string = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
var regex = /^data:.+\/(.+);base64,(.*)$/;

var matches = string.match(regex);
var ext = matches[1];
var data = matches[2];
var buffer = new Buffer(data, 'base64');
fs.writeFileSync('data.' + ext, buffer);

#2


20  

Try this

尝试这个

var dataUrl = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
var buffer = new Buffer(dataUrl.split(",")[1], 'base64');

#3


3  

I also met such questions (parsing and validating data URL) recently and found the following workaround: https://gist.github.com/bgrins/6194623

我最近也遇到了这样的问题(解析和验证数据URL)并找到了以下解决方法:https://gist.github.com/bgrins/6194623

I created 2 packages to make working with data URL easier in the code. Here they are: https://github.com/killmenot/valid-data-url
https://github.com/killmenot/parse-data-url

我创建了2个包,以便在代码中更轻松地处理数据URL。它们是:https://github.com/killmenot/valid-data-url https://github.com/killmenot/parse-data-url

Check out examples

查看示例