[英]Getting text of PNG from Postgres DB and sending image to front-end React
我有一个带表:“ buildings”的postgreSQL服务器,它包含一个列:“ testimg”,其数据类型为“文本”。 文本是PNG文件的文本。 我有一个成功连接到数据库的Express.js后端应用程序,并且创建了一个Route,可以读取此列(第1行)以显示其中包含的文本。 我不知道如何将其作为图像文件发送到我的前端React应用程序。
React应用程序已连接到路线,我知道如何调用路线并获取标头和所有信息。 我也知道我可能需要编码为base 64,但是我不确定。 我已经进行了一些挖掘,这是我到目前为止的工作。
//in my express app:
router.get('/test_image', ( req, res, next ) => {
client.query( "select testimg from buildings;" ).then( img_data => {
let base_64_string = img_data.rows[1].testimg + "\n";
let img = Buffer.from( base_64_string, 'base64' );
res.writeHead(
200, {
'Content-Type': 'image/png',
'Content-Length': img.length
})
res.end(img);
} )
})
//in my react app:
let img_query = null;
fetch( '/api/sites/test_image' )
.then( res => { img_query = res;} )
.catch( ( err ) => console.log( 'error:',err ) )
这给了我一个带有“ ReadableStream”正文的响应。 不知道我是否要按照正确的方式进行操作,但是最终需要获取“ img_query”以包含我的testimg.png。
这给了我带有“ ReadableStream”正文的响应
那是意料之中的。 来自MDN的响应body
是A simple getter used to expose a ReadableStream of the body contents.
您可以使用一种可用的方法来读取ReadableStream
。 在这种情况下,您可以使用text
方法。 从MDN
获取响应流并读取它以完成操作。 它返回一个用
USVString
(文本)解析的承诺。
fetch( '/api/sites/test_image' )
.then( res => res.text() )
.then( base64img => {
// base64img is the base64 string
})
.catch( ( err ) => console.log( 'error:',err ) )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.