简体   繁体   中英

Pass Javascript data from one function to another

I need to get an image file and post it using http in angular. Angular does not model files so I need a separate function to grab the data.

How can I pass data from this function to my http request?

var f = document.getElementById('imageFile').files[0],
    r = new FileReader();
r.onloadend = function(e){
  var data = e.target.result;
  //***********************************************
  // This is where my data is
  //***********************************************

}
r.readAsArrayBuffer(f);

var request = $http({
  method: "post",
  url: "/data/addToStore.php",
  data: {
    product_code: $scope.product_code,
    product_name: $scope.product_name,
    autoship_price: $scope.autoship_price,
    regular_price: $scope.regular_price,
    product_category_main: $scope.product_category_main,
    product_desc: $scope.product_desc,
    cat: $scope.cat,
    /* ********************************************
    This is where I need to get my data to
    imageFile: $SOMETHING
       ********************************************  */
  },
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});

As per my comment above:

var fileData = null;
var f = document.getElementById('imageFile').files[0],
    r = new FileReader();
r.onloadend = function(e){
  fileData = e.target.result;
  //***********************************************
  // This is where my data is
  //***********************************************

}
r.readAsArrayBuffer(f);

var request = $http({
  method: "post",
  url: "/data/addToStore.php",
  data: {
    product_code: $scope.product_code,
    product_name: $scope.product_name,
    autoship_price: $scope.autoship_price,
    regular_price: $scope.regular_price,
    product_category_main: $scope.product_category_main,
    product_desc: $scope.product_desc,
    cat: $scope.cat,
    imageFile: fileData
  },
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});

You could refactor that into a method callback on the scope object:

$scope.getFile = function (){
    var f = document.getElementById('imageFile').files[0];
    var r = new FileReader();
    r.onloadend = function(e){
        var data = e.target.result;
    }
    return r.readAsArrayBuffer(f);
}

var request = $http({
  method: "post",
  url: "/data/addToStore.php",
  data: {
    product_code: $scope.product_code,
    product_name: $scope.product_name,
    autoship_price: $scope.autoship_price,
    regular_price: $scope.regular_price,
    product_category_main: $scope.product_category_main,
    product_desc: $scope.product_desc,
    cat: $scope.cat,
    fileData: $scope.getFile()
  },
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM