Image upload to S3 with Meteor and React


#1

Hey guys, I’m working on implementing an image upload with React and Meteor to Amazon S3 through Slingshot package
So far I have this code:

import React, { Component } from 'react';
import { Meteor } from 'meteor/meteor';

export default class Profile extends Component {
    componentDidMount() {
        Slingshot.fileRestrictions('avatar', {
            allowedFileTypes: ["image/png", "image/jpeg", "image/jpg"],
            maxSize: 2 * 500 * 500
        });
    }
    upload() {
        let userId = Meteor.user()._id;
        let metaContext = { avatarId: userId };
        let uploader = new Slingshot.Upload("UsersAvatar", metaContext);
        uploader.send(document.getElementById('input').files[0], function (error, downloadUrl) {
            if (error) {
                alert (error);
            } else {
                Meteor.users.update(Meteor.userId(), {$push: {"profile.avatar": downloadUrl}});
            }
        });
    }
    onSubmit() {
        let avatarUrl = downloadUrl;
        Meteor.users.update(Meteor.userId(), {
            $set: {profile: avatarUrl}
        });
    }
    render() {
        return (
            <div className="container">
                <form>
                    <input type="file" id="input" onChange={this.upload.bind(this)} />
                    <button type="submit" onClick={this.onSubmit.bind(this)}>Upload</button>
                </form>
            </div>
        )
    }
}

When going through registation proccess, I create a user like so:

Accounts.createUser({
            email: email,
            password: password,
            profile: {
                avatar: 'https://www.example.com/no-image.jpg'
            }
        }

As you can see I add a custom field to manage user’s avatar with ability to upload and change it and Profile component should do the trick. The issue is that my $set function in onSubmit() {} method doesn’t update the avatar field as it suppossed to do, but the image upload works fine, I can see those images stored in my bucket, so it setted up correctly. In other words I would be happy if someone will tell me how can I update avatar field after image is uploaded. Any help and thoughts would be highly appreciated!


#2

Maybe try to $set instead of $push in the uploader.send callback function. This meteorchef article might be helpful aso https://themeteorchef.com/recipes/uploading-files-to-amazon-s3/


#3

Thank for replying! Yeah, the problem was with $push, I just changed it to $set and it works great right now, but somehow it didn’t work when I started this topic though. Maybe it’s something with S3 itself as I know it requires a couple of hours to set up the bucket properly.