我需要获取一个图像文件并使用http in angular发布。 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' }
});
答案 0 :(得分:0)
根据我上面的评论:
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' }
});
答案 1 :(得分:0)
您可以将其重构为范围对象上的方法回调:
$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' }
});