以下是我的服务代码,该代码正在保存图片 -
angular.module("app").service('fileUpload', ['$http', function ($http) {
return {
uploadFileToUrl: function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(response){
return response;
})
.error(function(){
});
}
}
}]);
在我的控制器中,我有以下代码 -
// Code for Image handling - START
if ($scope.myFile) {
var file = $scope.myFile;
console.log('file is ' + JSON.stringify(file));
var uploadUrl = "/api/fileUpload";
console.log("__FILE UPLOAD INFO__CHECK");
console.log(fileUpload.uploadFileToUrl(file, uploadUrl));
}
// Code for Image handling - END
我希望在console.log("__FILE UPLOAD INFO__CHECK");
之后的console.log返回数据,但在控制台中undefined
虽然我从AJAX请求中获得了控制台中的成功响应 -
{
"success": true,
"old_path": "/tmp/ddde0cf3b8a8e4fa83a92b361e814394",
"new_path": "/MYPROJECT_PATH/uploads/ddde0cf3b8a8e4fa83a92b361e814394.png",
"save_image_name": "ddde0cf3b8a8e4fa83a92b361e814394.png"
}
让我知道我在回调中做错了什么?
答案 0 :(得分:1)
它是异步的,所以你应该使用回调函数。
angular.module("app").service('fileUpload', ['$http', function ($http) {
return {
uploadFileToUrl: function(file, uploadUrl, successCb, errorCb){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(response){
if(successCb){
successCb(response);
}
})
.error(function(){
if(errorCb){
errorCb();
}
});
}
}
}]);