Angularjs - What is the best practice when uploading images?

Asked

Viewed 504 times

5

I implemented this solution to upload 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 didn’t particularly like this solution, but there are positive points in it. If an image fails, they all fail (which is expected). But I am having problems with heavier images. What is the best practice when uploading these images? I thought of raising once at a time, always invoking the next one in the callback of the current one, 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?

1 answer

4

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

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

  • One queue with buffer and limitation of shipments in parallel.
    Perks: Better bandwidth usage, better 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}
        })
   }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.