21

I am trying to upload a file with AngularJS. This is my code:

HTML

<input type="file" file-model="myFile"/>
<button ng-click="uploadFile()">upload me</button>

JavaScript

$scope.uploadFile = function(){
    var file = $scope.myFile;
    var uploadUrl = "http://admin.localhost/images/patanjali/";
    VariantService.uploadFileToUrl(file, uploadUrl);
};

VariantService.uploadFileToUrl = function(file, uploadUrl){
    var fd = new FormData();
    fd.append('file', file);
    $http.post(uploadUrl, fd, {
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
    })
    .success(function(){
        alert ('success');
    })
    .error(function(){
    });
}

Although I can see the ('success') alert in my service, the file is not saving in the location provided in controller.

Can someone help me? What is missing?

Badacadabra
  • 8,043
  • 7
  • 28
  • 49
Devesh Agrawal
  • 8,982
  • 16
  • 82
  • 131
  • possible duplicate of [File Upload using angularjs](http://stackoverflow.com/questions/18571001/file-upload-using-angularjs) – Dexygen Jun 26 '15 at 16:29
  • 4
    _file is not saving_ - Well, that's a server-side problem, isn't it? It would be a good idea to tell us what library you use. Where does `file-model` come from? – a better oliver Jul 05 '15 at 10:31
  • 2
    What are you using server side to handle the saving of the file? To me it sounds like you are receiving and error there but have a good design in place so that it is swallowed or logged service side but still returns 200 to the client. This is good for security reasons. What we do is attach an error property to the response object and check if it is null to verify success. If it's not there was an error and the application reacts appropriately. If you let us know what you are using on the backend we can get a better idea of how to help. – tuckerjt07 Jul 08 '15 at 00:46

4 Answers4

13

It looks like you're using code from this jfiddle for your app:

myApp.service('fileUpload', ['$http', function ($http) {
    this.uploadFileToUrl = function(file, uploadUrl){
        var fd = new FormData();
        fd.append('file', file);
        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(function(){
        })
        .error(function(){
        });
    }
}]);

While properly configured, this is only for posting data from the client side; the server also needs to be configured to accept/save the data. How you do this depends on your back-end tech stack.

6

I had same issue. I tried following code and my problem was solved.

var req = {
    method: 'POST',
    url: url,
    headers: {
        'Content-Type': "application/json",
    },
    data: data,
    transformRequest: function(data, headersGetter) {
        var formData = new FormData();
        angular.forEach(data, function(value, key) {
            formData.append(key, value);
        });
        var headers = headersGetter();
        delete headers['Content-Type'];
        return formData;
    }
}

$http(req)
    .success(function(response) {
        $scope.Models = response;
    })
    .error(function(data, status, headers, config) {

        // called asynchronously if an error occurs
        // or server returns response with an error status.
        alert(data);
    });
Pradeep
  • 3,093
  • 17
  • 21
Maulik Parmar
  • 857
  • 10
  • 15
1

$scope.setFiles = function (element) {
    $scope.$apply(function (scope) {
        $scope.files = [];
        for (var i = 0; i < element.files.length; i++) {
            scope.files.push(element.files[i])
        }
    });
};

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

    for (var i in $scope.files) {
        fd.append('file', $scope.files[i])
    }

    $http.post('http://admin.localhost/images/patanjali', fd, {
        transformRequest: angular.identity,
        headers: {
            'Content-Type': undefined
        }
    })
    .then(function successCallback(response) {
        
    }, function errorCallback(response) {
        
    });
};
<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js'></script>
<input type="file" valid-file ng-model-instant id="fileToUpload" onchange="angular.element(this).scope().setFiles(this)" />
<button ng-click="uploadFile()">Upload me</button>
JustCarty
  • 3,839
  • 5
  • 31
  • 51
0

You can use AngularJs modules for file uploader.The modules are very useful and very comfortable.

1) https://github.com/nervgh/angular-file-upload

2) https://github.com/danialfarid/ng-file-upload

Hazarapet Tunanyan
  • 2,809
  • 26
  • 30