[英]Pass Javascript data from one function to another
我需要獲取圖像文件並使用http以角度發布它。 Angular不對文件建模,因此我需要一個單獨的函數來獲取數據。
如何將數據從此函數傳遞到我的http請求?
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' }
});
根據我上面的評論:
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' }
});
您可以將其重構為作用域對象的方法回調:
$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' }
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.