Angular File上传formData

时间:2015-10-05 10:38:31

标签: javascript php angularjs

我正在使用Angular-File-Upload,问题是我无法将formData与文件一起发送。以下是我的代码:

 $scope.addProducts = function(){
        console.log($scope.product);
        ProductApi.addProduct($scope.product)
            .then(function(response){
                ngNotify.set('Your product has been added!', {
                position: 'bottom',
                duration: 2000
            });
                $scope.product_id = response.data;

                uploaderImages.uploadAll();
            })
            .catch(function(response){
                console.log(response.data);  
            })
}

上述代码的作用是,一旦表单提交,表单将通过api调用发送。响应将是product_id并且uploaderImages.uploadAll();被触发!!(此内容完美无缺)。以下是将文件发布到服务器的uploaderImages

var uploaderImages = $scope.uploaderImages = new FileUploader({
        url: '/api/productimg',
        onBeforeUploadItem: function(prod){
          var ids = $scope.product_id
          var prodid = { proid: $scope.product_id} ---> empty
          prod.formData.push(prodid)
          console.log($scope.product_id)   ----> product_id = 32
        },
        onCompleteAll: function(){
          console.log($scope.product_id); ----> product_id = 32
        },
        onSuccessItem: function(prodId,response,status,headers){

        }

    });

我不知道如何解决这个问题,proid:product_id返回[object Object],如果我将proid指定为固定整数,即proid:23,它就可以了。

请帮助!!!!!

1 个答案:

答案 0 :(得分:1)

您需要访问product_id的值,而不仅仅是响应有效负载:

$scope.product_id = response.data.product_id;

另外,因为您正在使用Promises,所以您需要链接您的方法。尝试:

$scope.addProducts = function(){
    console.log($scope.product);
    ProductApi.addProduct($scope.product)
        .then(function(response) {
            return ngNotify.set('Your product has been added!', {
                position: 'bottom',
                duration: 2000
        }, function(error) {
                console.log(error);
        }) // assuming this is async so add another then block below to execute once this is done
        .then(function(response) {
            $scope.product_id = response.data.product_id; // response.data will give you the whole response payload if the object returned is {product_id: 123}
            uploaderImages.uploadAll();
        });
}

请注意,错误处理程序是对第一个.then块(see the docs)的回调。