1

I have a toy react app that asks a toy nodejs server to do some image processing and return the result. The image processing server does this:

let result = path.join(__dirname, '/../../tmp/', name)
// .. write image to result
res.status(200).sendFile(result)

Logging this response on the client, I get:

{ data: "...binary image stuff...", status: 200, etc }

(1) How do I get that image data in data into an <img> tag in JSX? src={response.data}? that doesn't work

(2) Am I going about this wrong? Is the better way to just answer the filename in tmp then have the img src refer to that path? This idea seems better, except I'll get no chance to clean up the tmp file because I won't know when the img tag has finished getting it.

If there's a better way than (1) or (2) (like maybe a stream?) that would be great to understand, too. Thanks.

user1272965
  • 2,814
  • 8
  • 29
  • 49
  • 1
    Possible duplicate of [Is it possible to put binary image data into html markup and then get the image displayed as usual in any browser?](https://stackoverflow.com/questions/2429934/is-it-possible-to-put-binary-image-data-into-html-markup-and-then-get-the-image) – Brett DeWoody Jun 29 '17 at 14:15
  • Yes, see this question for more info - https://stackoverflow.com/questions/2429934/is-it-possible-to-put-binary-image-data-into-html-markup-and-then-get-the-image – Brett DeWoody Jun 29 '17 at 14:15
  • you need to actually read the file – Daniel Lizik Jun 29 '17 at 14:15
  • @BrettDeWoody - thanks for the ref. It makes sense as a dup, but could you give me any advice on the other aspect of the question? Should I just avoid sending a blob back, and write a server file? Or a stream? I'd like to learn how it's done by professionals. – user1272965 Jun 29 '17 at 14:20
  • One of the solutions in the other post has a good idea for how to tackle. You could have your nodeJS server return the image file, so you could use ``. More info here - https://stackoverflow.com/questions/17515699/node-express-sending-image-files-as-api-response, which is what it looks like you're already doing. – Brett DeWoody Jun 29 '17 at 14:48

1 Answers1

0

If you use express js you have send image files easily.

Example,

// server.js

var express = require('express');
var path = require('path');

app.use('/app', function(req, res){
    res.sendFile(path.resolve(__dirname, './html/app.html'));
})

app.use('/image', function(req, res){
    res.sendFile(path.resolve(__dirname, './images/img1.jpg'));
})

app.listen(9090, function(err){
    if(err){
        console.log(err);
    }
    console.log('Listening at localhost:9090');
})

// app.html   html/app.html

<html>
    <body>
        <img src='/image'/>
    </body>
</html>

// img1.jpg images/img1.jpg
Your images has inside this folder. 

Run your server and hit http:localhost:9090/app the app.html is open with image.

I hope this is useful for you.

Vasi
  • 1,147
  • 9
  • 16