Angular文件上传formData

Angular File upload formData

本文关键字:formData 文件 Angular      更新时间:2023-09-26

我使用的是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_iduploaderImages.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:23,它的工作。

请帮助! !

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

$scope.product_id = response.data.product_id;

同样,因为你在使用promise,你需要链接你的方法。试一试:

$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块的回调(参见文档)。