简体   繁体   English

如何在 API 中插入图像?

[英]How can I insert an image in API?

I have written very simple API with node.js and I want to insert images in the objects that can be accessible in the front-end anyone know how to do that?我写了非常简单的 API 和 node.js,我想在前端可以访问的对象中插入图像,有人知道该怎么做吗?

If you want to send image as binary data, you can use res.sendFile function.如果要将图像作为二进制数据发送,可以使用 res.sendFile function。

Below is an example that checks that req.user exists and then sends either JSON with a link to the image or the image itself.下面是一个示例,它检查 req.user 是否存在,然后发送带有图像链接的 JSON 或图像本身。 If the image is small it may be better to send a base64 encoded version.如果图像很小,最好发送 base64 编码版本。

app.get('/info', function(req,res){
    if(req.user){
        res.status(200).json({
            'imageName':'some image',
            'imageUrl':'/someImageUrlOnlyForAuthorizedUsers.jpg'
        });
    } else {
        res.status(401).send('Authorization required!');
    }
});

app.get('/someImageUrlOnlyForAuthorizedUsers.jpg', function(req,res){
    if(req.user){
        res.sendFile('./mySecretImage.jpg');
    } else {
        res.status(401).send('Authorization required!');
    }
});

If you want to create an object with the information in base 64 and with this insert it in the frontend, what you have to do is:如果您想使用 base 64 中的信息创建一个 object 并将其插入前端,您需要做的是:

const fs = require('fs');

let buff = fs.readFileSync('/someImageUrlOnlyForAuthorizedUsers.jpg',{encoding: 'base64'});
let base64data = buff.toString('base64')

Then you can return this object in the api and once you capture it in the frontend I'll show you an example:然后你可以在 api 中返回这个 object ,一旦你在前端捕获它,我会给你看一个例子:

<img src="data:image/png;base64,"+base64data">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将图像插入pdf而不保存到文件中? - How can I insert an image into a pdf without saving either to a file? 如何将图片发送到 Discord API 请求内容 - How can I send a image into Discord API request content 如何将画布对象转换为图像以作为 API 响应发送? - How can I transform a canvas object into an image to send as an API response? 如何通过邮寄将图像二进制文件发送到 API? 节点 - how can I send an image binary via post to an API? nodejs 如何使用他们的 API 将有效图像保存到 Github? - How can I save a valid image to Github using their API? 如何使用 nodejs 将我从 api 获得的数据插入到 mysql 中? - how can i insert data i got from api into mysql using nodejs? 如何将邮递员的值正确插入我的Node API - How can i insert properly values from postman to my Node API 如何调用google-bigquery同步删除和插入API? - How can i call google-bigquery delete and insert API's synchronously? 我如何将 JSON 插入 Azure SQL DB 中的 Z3B2819DD4C24EDA2FAF2052 API - How can i insert JSON into Azure SQL DB in Node.js (REST API) 如何将 JSON 中的数据插入 NodeJS 中的 const 变量以使用 API? - How can I insert data from a JSON to a const variable in NodeJS for using an API?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM