Nyxynyx
Nyxynyx

Reputation: 63687

Show Image after Image has been uploaded using CollectionFS

Images are uploaded to AWS S3 using Meteor.js and CollectionFS. The image to be uploaded is selected via a file input field.

'change .upload-input': function() {
    Images.insert(imageFile, function(err, fileObj) {
        Albums.update({_id: albumId}, {$set: { 
            'photo': BASE_URL + fileObj._id + 'photo.jpg'
        }})
    })
}

On the same page, we have an img with the src set to display the URL of the newly uploaded image.

{{#with album}}
    <img src="{{ photo }}">
{{/with}}

Problem: However the page tries to load this new image before its upload to S3 AWS is completed, giving an error

GET https://s3.amazonaws.com/myBucket/images/2nkLHcHsqxYrqW3hM-photo.jpg 403 (Forbidden)

The image loads on the page after refreshing the page.

How can we avoid loading the image before its uploaded entirely to S3?

Upvotes: 0

Views: 488

Answers (2)

Tom Kelsey
Tom Kelsey

Reputation: 143

I'm afraid I haven't used CollectionFS but, as suggested by user3452997, you could make use of the HTML5 FileReader API to preview the image with something like this:

'change .upload-input': function(e) {
    var file = e.target.files[0];
    // Rudimentary check that we're dealing with an image
    if (file && file.type.substring(0,6) === 'image/') {
        var reader = new FileReader();
        reader.onload = function() {
            $('#imgId').attr('src', reader.result);
        }
    }
}

The user would then see a local version of the image until they refreshed the browser, by which time the remote image would have hopefully uploaded.

Alternatively, I guess you need some sort of callback as to when CollectionFS is done with the upload.

If CollectionFS doesn't provide that, I guess a really hacky solution would be to create a helper that returned the photo after a delay (e.g. within a setTimeout) so that it has time to upload.

Upvotes: 2

juliancwirko
juliancwirko

Reputation: 1282

In case of AWS-S3 You could try https://atmospherejs.com/edgee/slingshot

See "Show uploaded file before it is uploaded" section

Upvotes: 0

Related Questions