如何在sails.js中或通常在服务器端JavaScript中将图像转换为base64编码的数据URL? [英] How do I convert an image to a base64-encoded data URL in sails.js or generally in the servers side JavaScript?

查看:78
本文介绍了如何在sails.js中或通常在服务器端JavaScript中将图像转换为base64编码的数据URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 sails.js 中制作一个小应用程序,我需要将图像存储在数据库中。为此,我需要将图像转换为base64编码的数据URL,以便我可以将其保存为我的sails模型中的字符串。但是,我不知道如何以这种形式转换它。所有较早的问题都是关于将图像转换为base64编码的数据URL的问题,他们回答了有关在客户端进行此操作的问题。但是,我想在服务器端执行此操作,而我将通过发布请求获取图像。我怎样才能实现这个目标?

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?

推荐答案

据我所知,您希望将文件转换为base64编码的字符串。无论文件是否为图像,都无关紧要。

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

用法:

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

来源

这篇关于如何在sails.js中或通常在服务器端JavaScript中将图像转换为base64编码的数据URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆