Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

node.js - How do I convert an image to a base64-encoded data URL in sails.js or generally in the servers side JavaScript?

I am making a small app in sails.js and I need to store images in database. For that, I need to convert an image to a base64-encoded data URL so that I can save it as a string in my sails models. However, I don't know how to convert it in this form. All the older questions asked about converting an image to base64-encoded data URLs, and they answer this about doing it on the client side. However, I want to do it on the server side while I will be getting the image through a post request. How can I achieve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As I understand you want to convert a file into base64 encoded string. Whether the file is image or not, that does not matter.

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');
}

Usage:

var base64str = base64_encode('kitten.jpg');

Source


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...