Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload a file with AngularJS?

Tags:

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?

like image 912
Devesh Agrawal Avatar asked Jun 26 '15 16:06

Devesh Agrawal


2 Answers

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.

like image 75
Zack Schuster Avatar answered Nov 13 '22 18:11

Zack Schuster


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);
    });
like image 30
Maulik Parmar Avatar answered Nov 13 '22 18:11

Maulik Parmar