2016-11-18 63 views
-1

我正在尝试为上传用户输入做一个简单的Angular表单。其中一个步骤涉及选择图像。我试图从远程源获取图像,然后将其上传到服务器。试图从onload()调用方法,我不知道是不是被告知方法

app.controller('submissionFormController', function ($http) { 
this.formIsVisible = false; 
... 
this.sub = { //this Object contains the data entered into the form 
      }; 

this.uploadImage = function(img){ 
    this.sub.imgfile = img; 
}; 

this.downloadImage = function() { 
    url = this.sub.imgurl; 
    var filename = url.substring(url.lastIndexOf("/") + 1).split("?")[0]; 
    var xhr = new XMLHttpRequest(); 
    xhr.responseType = 'blob'; 

    xhr.onload = function() { 
     this.uploadImage(xhr.response); 
     console.log("Image fetched!"); 
    }; 

    xhr.open('GET', url); 
    xhr.send(); 
}; 
}); 

当执行代码时,我得到了以下错误:

Object doesn't support property or method 'uploadImage'

+0

@trincot更多信息虽然你链接的问题让我的*什么*走错了一个好主意,它没有给出一个特别简洁的想法*如何解决它*。我不确定将此作为重复是否是正确的过程 - 我认为,这样做可以帮助那些遇到同样问题的人解决问题。 – UrhoKarila

+0

有很多方法。这里是一个:'xhr.onload = function(){ ...} .bind(this);'。 – trincot

+0

谢谢,那就是诀窍!尽管如此,我仍然支持我早先的断言 - 这个问题不应该被标记为重复,并且您的评论确实[应该已经被做出了答案](http://meta.stackoverflow.com/a/297069/1673882) 。 – UrhoKarila

回答

0

有很多方法的。这里是一个:

xhr.onload = function() { ... }.bind(this); 

你可以找到在这个question & answer

相关问题