What is the best way to transfer an excel file to a server using AngularJS in a Django project?

I am experiencing an issue with uploading a file to the server. The variable files in the for loop is showing up as undefined during debugging. Please review the directive to ensure it is correct.

HTML

 <input type="file" accept=".xlsx" file-model/>
 <button ng-click="upload()">upload me</button>

fileModel directive

app.directive('fileModel', function () {
    return {
        restrict: 'A',
        transclude: true,
        link: function($scope, $element) {
          var fileInput = $element.find('input[type="file"]');
          fileInput.bind('change', function(e) {               
            $scope.notReady = e.target.files.length == 0;
            $scope.files = [];
            for (var i in e.target.files) {
              if (typeof e.target.files[i] == 'object')       
                  $scope.files.push(e.target.files[i]);
            }
          });
        }
    };
  });

Controller

 $scope.upload = function() {        
      var uploadUrl =  'someurl';
      UtilityService.upload($scope.files, $scope.user, uploadUrl);
  };

Service

function UtilityService($http, $rootScope) {

      var service = {};
      service.upload=upload;

      function upload(files, user, uploadUrl) {
      var formData = new FormData();
      for (var i in files) {
        formData.append('file_' + i, files[i]);
      }

      formData.append("UserId", user.id);
      formData.append("UserRole", user.roles);

      $http({
          method: 'POST',
          url: config.server +uploadUrl,
          enctype: "multipart/form-data",
          data: formData,
          headers: {
            'Content-Type': undefined,
          },
          transformRequest: angular.identity
        })
        .success(function(data, status, headers, config) {
          service.data = data;

        });
    }
    return service;
  }

Answer №1

It seems like the issue lies in this particular line - var fileInput = $element.find('input[type="file"]');

I am uncertain as to why there is a need to search for anything. It appears that $element already represents the file input element.

Here is an updated version of the directive:

app.directive('fileModel', function () {
    return {
        restrict: 'A',
        transclude: true,
        link: function($scope, $element) {
          var fileInput = $element;
          fileInput.bind('change', function(e) {               
            $scope.notReady = e.target.files.length == 0;
            $scope.files = [];
            for (var i in e.target.files) {
              if (typeof e.target.files[i] == 'object')       
                  $scope.files.push(e.target.files[i]);
            }
          });
        }
    };
  });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering the error message "handleChange is not a function" when trying to select a date in Material UI

Encountering an error message 'handleChange is not a function' when selecting a specific date in the DatePicker component. The DatePicker component is nested within the Controller component of react-hook-form. The expected behavior is to display ...

What is the best way to reset scope in one controller while working from another controller in AngularJS?

Currently, I am in the process of developing a basic messaging application using AngularJS on jsFiddle. The functionality is mostly functioning correctly except for my "clearAlerts()" method which does not seem to be working as expected. As I am new to Ang ...

Displaying client-side filtered rows in a jqGrid with postData filter upon initial loading

Our website includes a jqGrid that initially retrieves its rows using the built-in ajax fetch feature, returning a json object. We then apply filtering and searching on the client side by creating custom functions to generate postData filters. However, we ...

How to Fix: jQuery UI Autocomplete Suggestions Remaining Open After Selection

I'm experiencing an unusual issue with a jQuery UI autocomplete feature. I have it set up so that when the text field is focused, a list of all options in the autocomplete appears. While this works as intended, selecting an item by clicking on it caus ...

Why is it important to use linting for JavaScript and TypeScript applications?

Despite searching extensively on Stack Overflow, I have yet to find a comprehensive answer regarding the benefits of linting applications in Typescript and Javascript. Any insights or resources would be greatly appreciated. Linting has become second natur ...

Refactor Print Preview Graph Display Issue within Nested Vue Component

I seem to be having trouble accessing this function properly due to an error. I am unsure of how to troubleshoot this issue and determine the correct solution. Any guidance would be greatly appreciated. The component PerformanceDonut.vue is located within ...

Calculate the number of elements shared between two arrays using JavaScript

I am working with two arrays of objects and I need to determine how many different types of cars we have. The first array contains the IDs of all the cars, while the second array contains information about the types of cars. Here is the data: var arr = ...

Leverage the Power of Multiple Markers on Google Maps with API Integration

My project involves creating a WordPress site that displays one marker on a map and has a list of additional locations below it. I aim to remove the description under the map and replace it with a simple list of locations alongside markers on the map. ...

What is causing me to receive a Request Method of "GET" instead of "POST"?

I recently implemented the dropzone js library for uploading images and have a query regarding it. Is the POST method more suitable than GET when uploading an image? If yes, how can I rectify this? $(document).ready(function() { var myDropzone = new Dr ...

Tips for displaying content when clicking on the opener containing tables or div elements

This is a snippet of JavaScript code $(document).ready(function () { $(".show-content").hide(); $(".opener").click(function () { $(this).parent().next(".show-content").slideToggle(); return false; ...

Updating the state across various components proves to be a challenge when relying on both the context API and higher order components

I have been working on updating the application state using the context API instead of using Redux, as I do not require all of its features and want to avoid prop drilling. With TypeScript, I created a global context and a higher-order component (HOC) wrap ...

Adjusting the Depiction Camera Distortion in Three.js

In my top-down Three.js game, I'm currently using a Perspective Camera. However, I've noticed that it curves a bit too much because it's mainly for "first-person view". Is there a way to customize how objects bend or curve within the frustum ...

Is there a way to show a loading indicator while waiting for ajax to finish loading?

While waiting for my messages to finish loading, I'd like to display a loading spinner. The loading spinner is implemented in my Message.vue: import backend from '...' export default { mounted: function() { this.loadMessages(); }, ...

Disable the moving of the DIV button with a left-margin of 0px

Having a bit of a challenge here. I'm attempting to craft my own slider using jQuery along with some css and javascript. I've managed to get my slider functioning, moving a Div 660px to the left and right upon button clicks. However, I'm h ...

What is the best approach to preserving and retrieving a Three.js scene?

I've come across loaders for individual objects and elements, but is there a way to save and load entire scenes in three.js? ...

Exploring ways to retrieve a specific list item by utilizing the $index parameter in conjunction with dirPaginate and a Search

Currently, I am working with a list of objects that is being displayed using dirPaginate. I have successfully implemented a search functionality for one of the object fields, however, I am encountering an issue where the index starts from 0 when searchin ...

Changing array of strings to integers using AngularJS

I'm having trouble with converting an array like this: vm.array = ['214','2912','82']; I tried using the map function to convert the values to integers, but it didn't work as expected. vm.newar = vm.array.map(Numb ...

Issue with logical operator ""!"" functionality in ejs file

Take a look at this code snippet: <% if( !title || title!=="login"){ %> <div class="dashboard-main-cont"> <div class="navigation-option"> <a class="btn btn-primary navbtn" href=& ...

What can you do to prevent a div from taking up the entire page if its height is not specified?

Currently, I am experiencing an issue with my layout. I have a hidden div with a fixed position that becomes visible when a button on the page is clicked. Inside this div, there is a table of buttons for the user to choose from. The problem arises when I ...

Unable to use global modules in NestJS without importing them

Currently, I am in the process of integrating a global module into my nest.js project I have written a service as shown below: export interface ConfigData { DB_NAME: string; } @Injectable() export class ConfigManager { private static _inst ...