Base64 Nodejs中的ReadFile

bru*_*cio 41 javascript base64 image readfile node.js

我正在尝试从base64中编码的客户端读取图像.如何用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.
        });
    }
})
Run Code Online (Sandbox Code Playgroud)

但是,我收到了这个错误:

In read file
[Error: Path must be a string without null bytes.]
Run Code Online (Sandbox Code Playgroud)

*解决方案*

lwip 在open方法中接受缓冲区.

// 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
});
Run Code Online (Sandbox Code Playgroud)

Sjo*_*erd 92

我认为以下示例演示了您的需求:http://www.hacksparrow.com/base64-encoding-decoding-in-node-js.html

本文的精髓是这个代码部分:

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');
Run Code Online (Sandbox Code Playgroud)

  • `new Buffer`是多余的.如果未指定编码,则`fs.readFileSync`返回缓冲区.你可以做`fs.readFileSync([..]).toString('BASE64')`. (8认同)
  • 如果目标是创建base64编码的[数据URI](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs),解决方案有点短.实际数据是正确的,但字符串缺少`data:[<mediatype>] [; base64],`前缀. (6认同)

Mik*_*tin 29

最新和最好的方法:

const fs = require('fs');
fs.readFileSync('/path/to/file.jpg', { encoding: 'base64' });
Run Code Online (Sandbox Code Playgroud)

  • `fs.readFileSync('/path/to/file.jpg', {encoding: 'base64'})` 不会解码二进制文件...它相当于 `fs.readFileSync('/path/to/file.jpg' ', 'utf8')` 我们只是传递一个编码参数来获取字符串而不是缓冲区 (3认同)

小智 9

var fs = require('fs');

function base64Encode(file) {
    var body = fs.readFileSync(file);
    return body.toString('base64');
}


var base64String = base64Encode('test.jpg');
console.log(base64String);
Run Code Online (Sandbox Code Playgroud)