Meteor-CollectionFS icon indicating copy to clipboard operation
Meteor-CollectionFS copied to clipboard

Pass arguments to the transformWrite function

Open mildful opened this issue 11 years ago • 9 comments

Hi everyone.

I'm trying to save cropped images to MongoDB via GridFS. Server-side, I crop the image with graphicsMagick in the transformWrite function. But I would like to give parameters to this function according to the user cropInfos choice.

Here is how I do this client-side :

//At this point, I have a variable named 'cropInfos' which contains crop information I want to pass to the server while saving / transforming the file.
Avatars.insert(field.files[0], function (err, fileObj) {
    if (err) {
        //not valid file
        console.log(err);
    } else {
        Meteor.users.update(Meteor.userId(), {$set: {
            'profile.avatar.id': fileObj._id,
            'profile.avatar.settings': cropInfos
        }});
    }
});

And server-side :

function createThumb (fileObj, readStream, writeStream) {
    const avatarSettings = Meteor.user().avatar.settings; // error: Can't access Meteor.userId() here.
    const gm = Meteor.npmRequire('gm').subClass({imageMagick: true});
    gm(readStream, fileObj.name)
        .crop(avatarSettings.width, avatarSettings.height, avatarSettings.x, avatarSettings.y)
        .resize(120, 120, '!')
        .stream()
        .pipe(writeStream);
}

Avatars = new FS.Collection("avatars", {
    stores: [
        new FS.Store.GridFS("thumb", { transformWrite: createThumb })
    ],
    filter: {
        maxSize: 1000000, //1Mo
        allow: { contentTypes: ['image/*'] }
    }
});

But I can't access Meteor.user() here.

How can I do that ?

mildful avatar Nov 21 '15 11:11 mildful

couldn't you add the user's id to the fileObj when doing the insert and then:

function createThumb (fileObj, readStream, writeStream) {
    const avatarSettings = Meteor.users.findOne(fileObj.userid).avatar.settings;

miri-am avatar Nov 21 '15 12:11 miri-am

That's a good idea but it doesn't seems to work. I think CFS "rebuild" the object. I'll go further :)

mildful avatar Nov 21 '15 14:11 mildful

@mildful, have you solved the problem? I'm trying to achieve the same thing.

hinterlist avatar Nov 23 '15 23:11 hinterlist

Not yet, sorry.

mildful avatar Nov 24 '15 07:11 mildful

Here is my solution:

 Images = new FS.Collection('images', {
    stores: [
        new FS.Store.GridFS('thumbs', {
            transformWrite: function(fileObj, readStream, writeStream) {
                let metadata = fileObj.metadata || {};
                if (!metadata.transform) {
                    let size = 300;
                    metadata.transform = {
                        resize: [size, size + '^'],
                        gravity: 'Center',
                        extent: [size, size]
                    };

                    fileObj.update({
                        $set: { 'metadata': metadata }
                    });
                }

                let tm = gm(readStream).autoOrient();
                Object.keys(metadata.transform).forEach((name) => {
                    let args = metadata.transform[name];
                    tm = tm[name].apply(tm, Array.isArray(args) ? args : [ args ]);
                });

                tm.stream('PNG').pipe(writeStream);
            }
        }),
        new FS.Store.GridFS('original')
    ],
    filter: {
        maxSize: (1048576 * 4), // 5 mb in bytes
        allow: {
            contentType: ['image/*']
        }
    }
});

Basically I'm passing instructions how to crop image as metadata. If no instructions will be passed, it will save default rules in databases as metadata and use them.

At first I tried to attach instructions directly to store, like 'thumbs', but unfortunately CollectionFS will not generate store data if object with this key name is not empty.

hinterlist avatar Nov 25 '15 00:11 hinterlist

Are you using Object.defineProperties() to attach metadata to your file object ?

mildful avatar Nov 25 '15 21:11 mildful

Actually no, I'm just setting it when processing files.

        FS.Utility.eachFile(e, (item) => {
            let file = new FS.File(item);
            if (this.props.transform) {
                file.metadata = {
                    transform: this.props.transform
                };
            }

            Images.insert(file, (err, fileObj) => {
                if (err) {
                    this.props.onError(err);
                } else {
                    this.setState({ image: fileObj });
                    this.props.onUpload(fileObj);
                }
            });
        });

hinterlist avatar Nov 25 '15 21:11 hinterlist

Okay, thanks a lot ! I think this issue can be closed :)

mildful avatar Nov 25 '15 21:11 mildful

It would be best if we could attach information during transformwrite.

projectn00b avatar Nov 29 '15 01:11 projectn00b