0

I am taking in a png file from AFNetworking saving it to GridFS and then I would like to be able to retrive it at some point. Out of curiousity I logged the image before it entered GridFS and it looks like..

<89504e47 0d0a1a0a 0000000d 49484452 00000074 0000008c 08020000 0022391a   ...>

I save this in a buffer and then store it into GridFS.

When I am retrieving it via a GET request I log it again before sending it out and it appears to be in the same format. Then I attempt to do this

res.writeHead(200, {'Content-Type': 'image/png' });
gs.createReadStream(image).pipe(res); //using GridJS this it the syntax to read

When viewing this in a browser it just appears like an empty or broken image link. If I inspect the page source it appears to be just

If I never set the headers it just appears as hundreds of lines of

<89504e47 0d0a1a0a 0000000d 49484452 00000074 0000008c 08020000 0022391a   ...>

I feel like I am not converting a buffer right or something.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Michael Giba
  • 118
  • 4

1 Answers1

0
var http = require('http'),
   MongoDB = require("mongodb"),
   MongoClient = require("mongodb").MongoClient,
   GridStore = require("mongodb").GridStore;

http.createServer(function (req, res) {
    console.log("Serving request for file: " + req.url);
    MongoClient.connect("mongodb://localhost:27017/test", {}, function(err, db) {
        gridStore = new GridStore(db, req.url, "r");
        gridStore.open(function(err, gs) {
            if (err) {
                console.log("error in open: " + err);
                return;
            }

            res.writeHead(200, {'Content-Type': 'image/png'});
            var s = gs.stream(true);
            s.pipe(res);
        });
    });

}).listen(8124, "127.0.0.1");

console.log('Server running at http://127.0.0.1:8124/');

I can successfully run server and serve the png files successfully to the browser using the code pasted above. However since, you are saying that raw contents of the source does appear on client side when you do a "see source". I would suggest trying the code I wrote and see if that has the same issues.

aks
  • 720
  • 4
  • 9