我有一个带有表“buildings”的 postgreSQL 服务器,它包含一个列:“testimg”,数据类型为“text”。文本是 PNG 文件的文本。我有一个成功连接到我的数据库的 Express.js 后端应用程序,并且我创建了一个可以读取此列(第 1 行)以显示包含的文本的路由。我不知道如何将其作为图像文件发送到我的前端 React 应用程序。
React 应用程序连接到路由,我知道如何调用路由并获取 header 和所有内容。我也知道我可能需要编码成 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。
最佳答案
This gives me a response with a body of "ReadableStream"
这是预期的。来自 MDN body
的响应是 A simple getter used to expose a ReadableStream of the body contents.
您可以使用一种可用的方法来读取 ReadableStream
。在这种情况下,您可以使用 text
方法。来自MDN
Takes a Response stream and reads it to completion. It returns a promise that resolves with a
USVString
(text).
fetch( '/api/sites/test_image' )
.then( res => res.text() )
.then( base64img => {
// base64img is the base64 string
})
.catch( ( err ) => console.log( 'error:',err ) )
关于javascript - 从 Postgres DB 获取 PNG 文本并将图像发送到前端 React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55987242/