Yeats
Yeats

Reputation: 2065

How to display new image in place of old after user uploads it?

There are two conditionals involved here:

1) When the user first enters the page, an image may not already be uploaded and nothing is shown.

2) An image may already be uploaded, in which case it should show and be overridden in real time when a new image is uploaded to replace it.

The whole uploading thing and displaying it right away is taken care of, it's just updating the image in case 2 that I'm struggling with.

When I upload the image, two things happen as can be seen here:

uploadImage('myDirective', d_canvas, 'image/png', function (error, downloadUrl) {
  if (! error) {
    Meteor.call('updateDatabase', versionId, downloadUrl)
    Session.set('imageAvailableAt', downloadUrl)
  }
})

First it calls a method to update the database to add the new url. Second it sets the same url in a Session variable. Note that no matter if an image exists or not, the url will be the same and it will overridden automatically if it does.

The image review looks like this in the template:

{{#with uploadedImage}}
  <div class="preview-of-uploaded-image">
    <img src="{{this}}">
  </div>
{{/with}}

And the helper:

var image = Session.get('imageAvailableAt')
return image

All right, this takes care of case 1, and it will display the image very neatly when it is uploaded.

But clearly nothing will show when an image is already uploaded here, and I have played with setting the same Session variable on onRendered, but then it won't update when I upload something new. I've tried different Session variables and conditionals but no luck. I've also tried Tracker.autorun but that doesn't work at all as described in the docs so I gave that up pretty quickly as well.

What should I do?

Upvotes: 1

Views: 58

Answers (1)

saimeunt
saimeunt

Reputation: 22696

You are facing a caching issue, the image URL is being cached by the browser and it will continue showing the old version for some time although the actual resource pointed at has been updated.

What you need to do to solve your problem is append a timestamp to the URL when modifying the collection server-side.

In your Meteor method, when updating the collection, be sure to decorate the URL with the current timestamp using something like :

Meteor.methods({
  updateDatabase: function(versionId, downloadUrl){
    check(versionId, String);
    check(downloadUrl, String);
    [...]
    Collection.update({
      downloadUrl: downloadUrl + "?timestamp=" + Date.now()
    });
  }
});

Upvotes: 1

Related Questions