ReadFile in Base64 Nodejs

前端 未结 3 452
既然无缘
既然无缘 2020-12-13 03:37

I\'m trying to read an image from client side encoded in base64. How to read with nodejs?

My code:

// add to buffer base64 image
var encondedImage =          


        
相关标签:
3条回答
  • 2020-12-13 04:03
    var fs = require('fs');
    
    function base64Encode(file) {
        var body = fs.readFileSync(file);
        return body.toString('base64');
    }
    
    
    var base64String = base64Encode('test.jpg');
    console.log(base64String);
    
    0 讨论(0)
  • 2020-12-13 04:20

    Latest and greatest way to do this:

    Node supports file and buffer operations with the base64 encoding:

    const fs = require('fs');
    const contents = fs.readFileSync('/path/to/file.jpg', {encoding: 'base64'});
    

    Or using the new promises API:

    const fs = require('fs').promises;
    const contents = await fs.readFile('/path/to/file.jpg', {encoding: 'base64'});
    
    0 讨论(0)
  • 2020-12-13 04:20

    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');
    
    0 讨论(0)
提交回复
热议问题