What is the best way to upload multiple files using AngularJS?

Seeking assistance with uploading multiple files using AngularJS... Any advice?

I currently have code that only allows for the upload of a single file. How can I modify it to support multiple file uploads?

Below is my HTML code snippet:

 <uib-tab index="5" heading="{{'uploadFile' | translate}}" select="tab.tabName = 'uploadFile'">
    <div class="form-group">
        <div class="row">
            <div class="col-md-12">
                <span class="dicom_uploader_title">{{'fileToUpload' | translate}}</span>
                <input type="file" class="dicom_uploader_input"  file-model="myFile" accept="*" multiple />
                <button ng-click="uploadFileNotDicom();"  class="btn btn-default">{{'uploadFile' | translate}}</button>
            </div>
        </div>
    </div>
    <div>
        <h4>{{'otherFilesForPatient' | translate}}</h4>
        <button ng-repeat="otherFile in otherFiles" class="btn btn-flat margin-item" ng-click="getDicomFile(otherFile.id,$index)" >{{otherFile.file_name}}.{{otherFile.extention}}</button>
    </div>
</uib-tab>

Here is a snippet of my AngularJS code:


$scope.uploadFileNotDicom = function(){
    var file = $scope.myFile;
    UploadFileService.upload_file(file,null,$scope.patientID).then(function(response){
        // Code for displaying success modal
    },function(err){
        // Code for displaying error modal
    })
};

Snippet from the UploadFileService service :


// Code for UploadFileService utilizing Angular

And here is an excerpt from my Yii2 PHP code snippet:


public function actionCreateFiles()
{
    // Code for handling file uploads in Yii2
}

Thank you!

Answer №1

It seems that the fileModel directive is not properly handling multiple file bindings upon change events.

Below is a functional example where the fileModel directive updates the model when there is a change. In the uploadFileService service, the files are added to the FormData object.

angular.module('app', [])
  .controller('uploadCTrl', uploadCTrl)
  .directive('fileModel', fileModelDirective)
  .service('uploadFileService', uploadFileService);

// Controller
uploadCTrl.$inject = ['uploadFileService'];

function uploadCTrl(uploadFileService) {
  var vm = this;
  vm.files = [];
  vm.upload = upload;

  function upload() {
    uploadFileService.upload(vm.files);
  }
}

// Directive
fileModelDirective.$inject = ['$parse'];

function fileModelDirective($parse) {
  return {
    restrict: 'A',
    link: function(scope, el, attrs) {

      var
        filesModel = $parse(attrs.fileModel),
        filesSet = filesModel.assign;

      el.bind('change', function() {

        var files = [];
        angular.forEach(el[0].files, function(item) {

          files.push({
            name: item.name,
            size: item.size,
            url: URL.createObjectURL(item),
            _file: item
          });

          scope.$apply(function() {
            filesSet(scope, files);
          });

        });

      });

    }
  }
}

// Service
uploadFileService.$inject = ['$http'];
function uploadFileService($http) {
  var _form
  Data = new FormData();
  var service = {
    upload: upload
  }

  return service;

  function upload(files) {
    _formData = new FormData();

    angular.forEach(files, function(file) {
      _formData.append('files', file._file, file.name);
    });
    
    // Post '_formData'
    console.log(_formData.getAll('files'));

  }

}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>

<body ng-app="app">

  <div ng-controller="uploadCTrl as up">
    <form>
      <input type="file" file-model="up.files" multiple />
      <br>
      <br>
      <button ng-click="up.upload()">UPLOAD</button>
    </form>
  </div>

</body>

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

Is there a way for my code to detect when a function and a timeout are in progress?

Is there a way to disable my button after just one click, or when the timeOut function is running? Currently, I have code that allows the button to be clicked only if my moneyValue is greater than money, and it's working perfectly. Now, within that sa ...

Issue with my "message.reply" function malfunctioning in Discord.JS

I'm currently learning how to use discord.Js and I am facing an issue with my message.reply function not working as expected. I have set up an event for the bot to listen to messages, and when a message containing "hello" is sent, it should reply with ...

What is the method to retrieve the total number of days in a moment-jalaali using NodeJS?

I'm trying to determine the number of days in the moment-jalaali package for NodeJS. Despite checking their API on GitHub, I couldn't find any reference to a specific method like numOfDay. ...

ERROR: Expo TaskManager Notifications [TypeError: Attempting to call an undefined function (near '...Notifications.presentLocalNotificationAsync...')]

I'm currently trying to figure out how to send notifications whenever a task is triggered, but I keep encountering an error that I can't seem to fix. Here's the error message: TaskManager: Task "background-fetch" failed:, [TypeError: unde ...

error in routing using koa-router with koa

I've been diving into learning Koa and trying out some basic exercises, but I'm having trouble implementing a simple routing feature. I followed the code from this tutorial and here's what I have so far: var koa = require('koa'); v ...

Is it correct to use React Router's useNavigate with a useEffect hook for navigation?

I am a beginner to React and I have been working on creating a loading/greeting page that automatically navigates to the next page after a few seconds. In React Router v6, there is a useful hook called useNavigate() which allows you to control navigation. ...

Guide to updating information in Firestore using Node.js, embedded in a map array

Encountered an issue with the following error message: Error: Unable to access 'set' property of undefined. I am attempting to update the endTime field in my script for each user, calculate total hours worked, and then update the 'totalTi ...

Error encountered during Jest snapshot testing: Attempting to destructure a non-iterable object which is invalid

I am currently facing an issue with my React codebase where I am attempting to create snapshot tests for a component. However, Jest is showing an error indicating that I am trying to destructure a non-iterable instance. Despite thoroughly reviewing the cod ...

Problem Encountered with Kendo Angular Grid during npm Installation

I've made the decision to incorporate kendo-angular-grid into my Angular 5.2 project. Despite Kendo's latest version being listed as 2.0.0, I encountered an issue where the command npm install --save @progress/kendo-angular-grid resulted in the i ...

Enhancing infinite scroll functionality with ajax integration

After implementing a method to enable infinite scroll on my website using the following function: window.onscroll = yHandler; function yHandler(){ var wrap = document.getElementById('wrap'); var contentHeight = wrap.offsetHeight; var yOffset = w ...

Guide to implementing PCF (SOFT) shadows with three.js

Is it possible to apply the PCF (SOFT) shadow type, like the one found in the Three.js online editor, to your renderer using javascript code? https://i.sstatic.net/x0QmH.png ...

The reducer I have is inexplicably returning undefined even though I'm certain it was added to combineReducers

After countless hours of debugging, everything seems to be in working order but the problem still persists. The main reducer file is located at reducers/index.js // @flow import { combineReducers } from "redux"; import blocks from "./blocks"; import user ...

Removing items in vue.js

I'm currently in the process of learning Vue.js. This is my first attempt at creating a small to-do application, and I am encountering issues with deleting each individual task upon clicking. Despite watching multiple YouTube tutorials, I have not bee ...

I'm currently working with ReactJS and attempting to retrieve JSON data from a REST API in JIRA, but I'm facing challenges in achieving this

I've been struggling for hours trying to understand why I am unable to access and transfer data in my array from the JSON data in JIRA using the REST API. Basically, I am attempting to retrieve the JSON data from the JIRA website via URL with Basic Au ...

Enhancing the efficiency of nested ajax calls loop

Disclaimer: While the final result is successful, I am struggling to comprehend the sequence in which a loop of nested ajax calls operates. Essentially, I have two ajax calls that fetch data from an external API using curl GET requests. They both rely on ...

Error: Unable to locate module: 'material-ui/styles/colors'

I encountered an issue with the code below, as it failed to compile: import React from 'react'; import { AppBar, Toolbar } from 'material-ui'; import { Typography } from 'material-ui'; import { MuiThemeProvider, createMuiThem ...

Expanding functionality: Steps to integrating a new endpoint into your AWS Amplify Express Server

I have created a REST express server using Amplify. Attempted to include two additional endpoints: // incorporating serverless express app.post('/myendpoint', function(req, res) { console.log('body: ', req.body) res.json(req.body) ...

Maximizing Code Reusability in Angular: Leveraging Services and Controllers

I am currently using Angular to create a commenting feature for a web application. There are two sections in the app where users can leave comments: Category and Product. Category Product Most of the commenting functionality is the same for both section ...

Test a JavaScript function within an Angular service using the Jasmine framework

I need to write a unit test for a JavaScript function within an Angular service using Jasmine. Here is the Angular service: angular.module("app.services").service("validationService", ["$q", function ($q) { this.validate = function (filter): ng. ...

Utilizing Numerous JavaScript Functions within jQuery

I've been facing a persistent issue and I'm seeking guidance on how to resolve it. I have developed a multipage Jquery similar to the one showcased below. However, whenever I try to reference a .js file that I have saved, the pages either fail t ...