I have a postgreSQL server with table: "buildings" and it contains a column: "testimg" with a data type of "text". The text is a PNG file's text. 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. I don't know how to send this as an image file to my Front-End React app.
The React app is connected to the route and I know how to call the route and get a header and all. I also know I probably need to encode into base 64 but I'm really not sure. 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". Not sure if I'm going about this the right way but I need to eventually get "img_query" to contain my testimg.png.
This gives me a response with a body of "ReadableStream"
That's expected. From MDN body
of response is A simple getter used to expose a ReadableStream of the body contents.
You can use one of the available methods to read the ReadableStream
. In this case you could use text
method. From 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 ) )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.