Jeanluca Scaljeri
Jeanluca Scaljeri

Reputation: 29097

How to serve (uploaded) images using Meteor

I have this Meteor application in which it is possible to upload images. The uploading parts seem to work. I store the images in .uploads. Now I would like to make these images accessable by the following URL

http://localhost:3000/uploads

After a bit of googling I was able to create the following server side code:

var fs = Meteor.require('fs');

if (Meteor.isServer) {
    WebApp.connectHandlers.stack.splice(0, 0, {
        route: '/uploads',
        handle: function (req, res, next) {

        var path = process.env.PWD + '/.' + req.originalUrl.substr(1);

        fs.readFile(path, {encoding: 'binary'}, function (err,data) {
            if (err) {
                throw err;
            }

            res.writeHead(200, {
                'Content-Type': 'image/png'
            });
            //res.setEncoding("binary"); // this method does not exist
            res.write(data);
            res.end();
        });
      }
   });
}

This code works, the path constructed is correct and in the browser I receive the 200 code, except it cannot display the image. Something is wrong with the data the browser receives. I checked the image on disk which is fine. So the code above must do something wrong with the data. Any suggestions what that might be?

Upvotes: 0

Views: 545

Answers (1)

Alban Lecocq
Alban Lecocq

Reputation: 329

Here is the code I found after googling (and works for me) a few days ago when I wanted to do what you need to do files are in .screenshots directory mapped to :

http://localhost:3000/screenshots 

code :

//directly serve screenshot files from /.screenshots dir
var fs = Npm.require('fs');
WebApp.connectHandlers.use(function(req, res, next) {
    var re = /^\/screenshots\/(.*)$/.exec(req.url);
    if (re !== null) {   // Only handle URLs that start with /screenshots/*
        var filePath = process.env.PWD + '/.screenshots/' + re[1];
        var data = fs.readFileSync(filePath, data);
        res.writeHead(200, {
                'Content-Type': 'image'
            });
        res.write(data);
        res.end();
    } else {  // Other urls will have default behaviors
        next();
    }
});

Upvotes: 1

Related Questions