totaljs / framework

Node.js framework
http://www.totaljs.com
Other
4.36k stars 450 forks source link

Use default image when image doesn't exist in FILE_STORAGE #713

Closed flashvnn closed 5 years ago

flashvnn commented 5 years ago

i use code bellow to display thumbnail for image,

exports.install = function () {
    FILE('/image/style/thumbnail/', image_thumbnail);
};
function image_thumbnail(req, res) {
    var id = req.split[3].replace('.' + req.extension, '');
    res.imagefs('files', id, function (image) {
        image.output(req.extension);
        image.quality(100);
        image.resizeAlign(120, 120, 'center');
    });
}

Everything work fine, when image doesn't exist it throw 404 page. How i can return a default image placed in public folder when image doesn't exist?

petersirka commented 5 years ago

@flashvnn you need to specify extensions ...

FILE('/image/style/thumbnail/', image_thumbnail, ['*.jpg', '.png', '.gif']);

or

FILE('/image/style/thumbnail/*.jpg', image_thumbnail);

or for all files:

FILE('/image/style/thumbnail/*.*', image_thumbnail);
flashvnn commented 5 years ago

Thanks for your fast reply, My issue is when user load image like /image/style/thumbnail/B20190701T000000039.jpg and if the file with ID B20190701T000000039 doesn't exist or removed in FILE_STORAGE , i want return other image instead of throw 404 page.

petersirka commented 5 years ago

This can be handle via system route 404 only:

ROUTE('#404', function() {
    var self = this;
    var compare = '/image/style/thumbnail/';
    if (self.uri.pathname.substring(0, compare.length) === compare) {
        // DEFAULT IMAGE
        self.file('YOUR_FILE_FROM_PUBLIC_DIRECTORY');
    } else {
        self.status = 404;
        self.plain('404: Resource not found');
    }
});
petersirka commented 5 years ago

In other words: if the file won't exist then the framework executes #404 route.

flashvnn commented 5 years ago

It work great, thanks you.