0

I'm trying to send a base64 encoded string to my server but the data binding I use is "" in the function to send it.

This is the code:

processFile: function(event) {
      var rawFile = event.target.files[0];
      var reader = new FileReader();
      reader.readAsDataURL(rawFile);
      reader.onload = function() {
        this.file = reader.result.split(',')[1];
      };
    },

So this.file contains the base64 string but when I access it in another function it's returning ""

What am I doing wrong here?

JrProgrammer
  • 108
  • 1
  • 11
  • You can use `ES6` like this: `reader.onload = () => { this.file = reader.result.split(',')[1]; }` – talkhabi Sep 02 '17 at 12:20
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Bert Sep 02 '17 at 16:24

1 Answers1

1

Try

processFile: function(event) {
      var rawFile = event.target.files[0];
      var reader = new FileReader();
      reader.readAsDataURL(rawFile);
      reader.onload = function() {
        this.file = reader.result.split(',')[1];
      }.bind(this);
    },

or

processFile: function(event) {
      var rawFile = event.target.files[0];
      var reader = new FileReader();
      reader.readAsDataURL(rawFile);
      var vm = this;
      reader.onload = function() {
        vm.file = reader.result.split(',')[1];
      };
    },
Reiner
  • 1,621
  • 1
  • 16
  • 22
  • Thanks, this worked. Could you explain why I have to instantiate "this"? – JrProgrammer Sep 02 '17 at 12:14
  • 1
    Unfortunately documentation is going away, which is why you were not allowed to link that. These days I have been marking these questions as a duplicate of this one: https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback – Bert Sep 02 '17 at 16:23
  • In my opinion one half of the vuejs questions is about scoping and one half about ajax and of course often they intersect. – Reiner Sep 02 '17 at 17:17