S
S
Stepan Kormilin2016-08-23 21:10:15
Angular
Stepan Kormilin, 2016-08-23 21:10:15

How to upload a file to the server using AngularJS?

Good day!
Tell me how to correctly organize the submission of the Angular form with the choice of an image file and the name of this image. The main problem is in downloading the file, I don’t understand how to do it.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Зелимхан Бельтоев, 2016-08-23
@Beltoev

Используйте готовое решение: https://github.com/danialfarid/ng-file-upload
Всё сведется к тому, что нужно будет в контроллер добавить сервис Upload, а уже в нём вызывать метод upload, передавая ему url адреса для загрузки и прочие параметры.
Решение только на первый взгляд сложное, но на деле там всё просто выходит =)

S
Stepan Kormilin, 2016-08-26
@Stepan13

Well, how many of these ready-made solutions I didn’t try, for some reason it didn’t work out, maybe the whole thing was in the features of the django backend. But each time I got a 400 error. As a result, the working implementation turned out like this.

$scope.uploadFile = function(file, title){
            var fd = new FormData();

            fd.append('title', title);
            fd.append('image', file);
            fd.append('hotel', $scope.hotel.id);
            fd.append('is_primary', false);

            return $http({
                url: '/api/v2/hotels/image/',
                method: 'POST',
                data: fd,
                headers: { 'Content-Type': undefined },
                transformRequest: angular.identity,
                transformResponse: function (data) {
                    data = JSON.parse(data);
                    return data;
                }
            })
            .success(function(data){
                $scope.images.push(data);
            });
        };

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question