Nodejs: How return different content types with same response (text and image)?

前端 未结 2 1065
独厮守ぢ
独厮守ぢ 2020-12-16 21:15

I\'m trying to learn nodejs and I thought the best way to do this would be to try doing some stuff without using express or any other non-core modules. I\'m stuck on trying

相关标签:
2条回答
  • 2020-12-16 22:01

    If you do response.write('<img src="my_pic.jpg"/>'); as mentioned above the image file would be sent only when browser sends GET for the image. It would become multi-part request.

    Or you can do it like this. It is possible to send your image in binary form in HTML. Use :

    <img src="data:image/gif;base64,imagedata">
    

    where imagedata is a base64 encoding of gif image. So do this in node.js :

    //Write text in response.
    content = get-image-file-contents;     //store image into content
    imagedata = new Buffer(content).toString('base64');    //encode to base64
    response.write('<img src="data:image/gif;base64,'+imagedata+'">');//send image
    response.end();
    

    Check here for correct image conversion NodeJS base64 image encoding/decoding not quite working

    This sends one response which sends both text and image. Only one header is required for response response.writeHead(200, {'content-type':'text/html'});

    0 讨论(0)
  • 2020-12-16 22:03

    You can only write one value to a given header, so the second header is overwriting the first. Two solutions are

    1. write out a url to the image in the html - will be slightly slower for the user (needing an extra http request to fetch the image), but depending on the use case this is normally acceptable and very simple to implement
    2. convert the image to a data-uri string and include this in the html as the source of the image. More complicated to implement than the first approach ( I don't know of any libraries for doing the conversion in node) and with negligible benefits.
    0 讨论(0)
提交回复
热议问题