AngularJS - What is the best practice when uploading images?

5

I've implemented this solution to upload the images:

MaquinaResource.save($scope.maquina, function (data, responseHeaders) {
   var formDataImage = new FormData();

   for(var i = 0 ; i < $scope.images.length; i++) {
       formDataImage.append('file', $scope.images[i].file);
   }

   if($scope.images.length > 0) {
      $http.post('rest/maquina/'+data.id+'/upload/imagem',    formDataImage, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
   }
}

I particularly dislike this solution, but there are good points in it. If an image fails, all fail (which is expected). But I'm having problems with heavier images. What is the best practice when uploading these images? I thought of uparing one at a time, always invoking the next in the current callback, but this would bring me a transactional problem (if an image fails the previous ones will already be saved). What is the best solution in these cases?

    
asked by anonymous 21.06.2016 / 15:36

1 answer

4

The answer will depend on the requirements of your application. What you implemented was a synchronous and linear process. You can implement:

  • A parallel and asynchronous upload process , where all files are uploaded at the same time. If necessary, implement a token to indicate the participation of this file in a group.
    Advantages : Simple implementation, if a file fails this does not mean that your process as a whole will be compromised. Disadvantages : Competition from all concurrent upload processes will cause delay to even the smallest file being received by the server.

  • A queue with buffer and Parallel upload limitation . Benefits : Best bandwidth usage, best user experience. Disadvantages : Implementation complexity.

Your code can be easily refactored to apply to the first type:

MaquinaResource.save($scope.maquina, function (data, responseHeaders) {
   var formDataImage = new FormData();

   for(var i = 0 ; i < $scope.images.length; i++) {
      $http.post('rest/maquina/'+data.id+'/upload/imagem', {file: $scope.images[i].file}, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
   }
}
    
21.06.2016 / 19:32