简体   繁体   English

从Postgres DB获取PNG文本并将图像发送到前端React

[英]Getting text of PNG from Postgres DB and sending image to front-end React

I have a postgreSQL server with table: "buildings" and it contains a column: "testimg" with a data type of "text". 我有一个带表:“ buildings”的postgreSQL服务器,它包含一个列:“ testimg”,其数据类型为“文本”。 The text is a PNG file's text. 文本是PNG文件的文本。 I have an Express.js back-end app that is sucessfully connected to my database, and I have a created a Route that can read this column (row 1) to reveal the text contained. 我有一个成功连接到数据库的Express.js后端应用程序,并且创建了一个Route,可以读取此列(第1行)以显示其中包含的文本。 I don't know how to send this as an image file to my Front-End React app. 我不知道如何将其作为图像文件发送到我的前端React应用程序。

The React app is connected to the route and I know how to call the route and get a header and all. React应用程序已连接到路线,我知道如何调用路线并获取标头和所有信息。 I also know I probably need to encode into base 64 but I'm really not sure. 我也知道我可能需要编码为base 64,但是我不确定。 I have done some digging and this is what I have so far. 我已经进行了一些挖掘,这是我到目前为止的工作。

//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 ) )

This gives me a response with a body of "ReadableStream". 这给了我一个带有“ ReadableStream”正文的响应。 Not sure if I'm going about this the right way but I need to eventually get "img_query" to contain my testimg.png. 不知道我是否要按照正确的方式进行操作,但是最终需要获取“ img_query”以包含我的testimg.png。

This gives me a response with a body of "ReadableStream" 这给了我带有“ ReadableStream”正文的响应

That's expected. 那是意料之中的。 From MDN body of response is A simple getter used to expose a ReadableStream of the body contents. 来自MDN的响应bodyA simple getter used to expose a ReadableStream of the body contents.

You can use one of the available methods to read the ReadableStream . 您可以使用一种可用的方法来读取ReadableStream In this case you could use text method. 在这种情况下,您可以使用text方法。 From MDN 从MDN

Takes a Response stream and reads it to completion. 获取响应流并读取它以完成操作。 It returns a promise that resolves with a USVString (text). 它返回一个用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM