Node return image stored in sqlite blob
I'm querying to an API using Restify
My SQLite database have a places table that has the following structure (id INTEGER, name TEXT, image BLOB)
I'm trying to output the response result as an image (the blob contains a jpeg image) but i haven't succeed so far.
In the browser after made the request i'm getting The image 'http://localhost:8080/place/1 cannot be displayed because it contains errors
I'm getting properly in the console the place name.
Here is my code:
var restify = require('restify');
function respond(req, res, next) {
var fs = require("fs");
var file = "./data.db";
var exists = fs.existsSync(file);
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database(file);
db.get("SELECT id, name, image FROM places WHERE id = ?", req.params.uid, function(err, row){
console.log(row.name);
res.header('Content-Type', 'image/jpeg');
res.end(row.image);
db.close();
});
next();
}
var server = restify.createServer();
server.get('/place/:uid', respond);
server.listen(8080, function() {
console.log('%s listening at %s', server.name, server.url);
});
UPDATE: The image is returned without troubles when i create the blob using the same [node-sqlite3][2] library. If i create the blobs using Ruby or Go (the ones that i had tested) the node-sqlite3 decoding doesn't work as expected.
UPDATE 2: Is seems and encoding issue but i can't figure out yet why node-sqlite3 can't decode blobs created with Ruby or Go.
I asked this question in SO too http://stackoverflow.com/q/31468221/1373105
I'm not familiar with Go or Ruby but using the official sqlite3 command line client I did:
sqlite> .open data.db
sqlite> CREATE TABLE places(id INTEGER, name TEXT, image BLOB);
sqlite> INSERT INTO places (id, name, image) VALUES (1, 'plant.jpg', readfile('plant.jpg'));
sqlite>.quit
Note that readfile is an extension built into the command line client only
Then I ran your code, navigated to the same URL in Firefox and Internet Explorer, and the image displayed fine.
I suspect that whatever method you are using to insert the image in Ruby or Go is causing the problem as you said above. In the sqlite3 command line client you could do:
SELECT writefile('out.jpg',image) FROM places WHERE id=1;
and see if out.jpg matches your original image that you inserted in Go or Ruby.
If i create the blobs using Ruby or Go (the ones that i had tested) the node-sqlite3 decoding doesn't work as expected.
This is the cause; you'll need to figure out how your Ruby and Go code is putting different data into the sqlite database.