[Django]-Angular Js File Upload

0👍

try this one…

$(document).ready(function(){
    $('#fileupload').fileupload({
        dataType: 'json'});
});

TestCtrl = function($scope){
    $scope.fileList = [];
    $('#fileupload').bind('fileuploadadd', function(e, data){
            $scope.$apply(
            $scope.fileList.push({name: file.name})
            );   
        data.submit();
    });

}

5👍

I can’t answer your question directly, except to say: make sure you have the data-url set on your input from the example on JSFiddle.

As an alternative, I would recommend angular-file-upload which I’ve used with success. It uses angular directives to accomplish the uploading. This pattern uses a little more code, but separates the concerns in your application so you Controller just glues things together, and your service actually talks to the outside world.

This will make your app easier to test:

<div ng-controller="FileUploadController">
  <h3>Upload a file</h3>
  <input type="file" ng-file-select="uploadFile($files)" />
</div>

And the javascript:

// define the app, include the file upload dependency
var app = angular.module('MyApp', ['ng', 'angularFileUpload']);

// controller to handle the file upload event
app.controller('FileUploadController', 
  function ($scope, $rootScope, FileUploadService) {
    var service = FileUploadService;
    /** 
     *  Handler to upload a new file to the server.
     */
    $scope.uploadFile = function ($files) {
      var $file = $files[0];
      service.uploadFile($file, function (error) {
        if (error) {
          alert('There was a problem uploading the file.');
        }
        // handle successfully-uploaded file
      })
    }
  });

// services should interact with the outside world
app.factory('FileUploadService', function ($http) {
  var api = {
    uploadFile: function (file, callback) {
      $http.uploadFile({
        url: '/some/remote/end/point/',
        file: file
      }).progress(function(event) {
        console.log('percent: ' + parseInt(100.0 * event.loaded / event.total));
      }).error(function (data, status, headers, config) {
        console.error('Error uploading file')
        callback(status);
      }).then(function(data, status, headers, config) {
        callback(null);
      });
    }
  }
  return api;
});

Leave a comment