Base64 Nodejs中的ReadFile [英] ReadFile in Base64 Nodejs
本文介绍了Base64 Nodejs中的ReadFile的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从base64编码的客户端读取图像。
如何阅读nodejs?
I'm trying to read an image from client side encoded in base64. How to read with nodejs?
我的代码:
// add to buffer base64 image
var encondedImage = new Buffer(image.name, 'base64');
fs.readFile(encondedImage, "base64", function(err, buffer){
if ( err ) {
console.log('In read file')
console.log(err)
} else {
// check err
lwip.open(buffer, 'jpg', function(err, image){
console.log('in open')
if ( err ) console.log(err)
if ( image ) console.log(image)
// check 'err'. use 'image'.
// image.resize(...), etc.
});
}
})
但是,我收到了这个错误:
But, I got this error:
In read file
[Error: Path must be a string without null bytes.]
* SOLUTION *
lwip
在open方法中接受缓冲区。
lwip
accept buffer in open method.
// add to buffer base64 image from step
var encondedImage = new Buffer(image.name, 'base64');
// check err
lwip.open(encondedImage, 'jpg', function(err, image){
// image.resize(..), etc
});
推荐答案
我认为以下示例演示了您的需求: http://www.hacksparrow.com/base64-encoding-decoding-in-node- js.html
I think that the following example demonstrates what you need:http://www.hacksparrow.com/base64-encoding-decoding-in-node-js.html
本文的精髓是此代码部分:
The essence of the article is this code part:
var fs = require('fs');
// function to encode file data to base64 encoded string
function base64_encode(file) {
// read binary data
var bitmap = fs.readFileSync(file);
// convert binary data to base64 encoded string
return new Buffer(bitmap).toString('base64');
}
// function to create file from base64 encoded string
function base64_decode(base64str, file) {
// create buffer object from base64 encoded string, it is important to tell the constructor that the string is base64 encoded
var bitmap = new Buffer(base64str, 'base64');
// write buffer to file
fs.writeFileSync(file, bitmap);
console.log('******** File created from base64 encoded string ********');
}
// convert image to base64 encoded string
var base64str = base64_encode('kitten.jpg');
console.log(base64str);
// convert base64 string back to image
base64_decode(base64str, 'copy.jpg');
这篇关于Base64 Nodejs中的ReadFile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文