Using Content-Disposition in ng-file-upload with AngularJS

Context:

I am currently working with ng-file-upload to submit two files separately using ngf-selects along with a Javascript object literal. The problem I'm facing is that when the request is sent, all the parts have their content-disposition set to form-data instead of what I expected, which was attachment for the files.

Query:

Is there a method for me to alter the content-disposition of the form components so that it shows as attachment for the files rather than form-data?

SCRIPT

Controller:

(function () {
  'use strict';

  angular
    .module('poc.fileUpload')
    .controller('SignupFileUpload', SignupFileUpload);

    SignupFileUpload.$inject = ['$scope','Upload', '$log', '$timeout','$location','URLS','SignupService','usSpinnerService','$anchorScroll'];

    function SignupFileUpload($scope, Upload, $log, $timeout, $location, URLS, SignupService,usSpinnerService,$anchorScroll) {
      // Your controller script goes here
    }
}());

HTML

 <!-- HTML code for file uploading form goes here --> 

Current Request: https://i.sstatic.net/OA7Iw.png

Answer №1

Despite the limitations of existing libraries, I needed to modify the content-disposition and other aspects, which I was able to achieve with guidance from this thread

While still leveraging ng-file-upload for various UI functions, I am now manually constructing the post in the controller.

(function () {
  'use strict';

  angular
    .module('poc.fileUploads')
    .controller('SignupFileUpload', SignupFileUpload);

    SignupFileUpload.$inject = ['$scope','Upload', '$log', '$timeout','$location','URLS','SignupService','usSpinnerService','$anchorScroll','$http'];

    function SignupFileUpload($scope, Upload, $log, $timeout, $location, URLS, SignupService,usSpinnerService,$anchorScroll,$http) {
      $log.debug('ENTERING SIGNUP UPLOAD CONTROLLER %s', JSON.stringify(this));

      var params = $location.search();
      var customerInfo = SignupService.getCustomerInfo();
      var uploadData = {};

      $log.debug('CUSTOMER INFO'+JSON.stringify(customerInfo));

      if (typeof Object.keys(customerInfo)[0] === 'undefined') {
        $log.debug('SIGNUP - Must provide customerInfo');
        $location.path('/signup');
      }

      $scope.uploadFiles = function(idFile,addressFile,form) {
        usSpinnerService.spin('spinner');

        $log.debug('Starting Upload Process to resource - ' + URLS.BASE + URLS.FILE_UPLOAD);

        $log.debug('Adding customerInfoPart to uploadData');
        uploadData.customerInfoPart = Upload.jsonBlob(customerInfo);

        $log.debug('Checking for files to upload');
        if (idFile) {
          $log.debug('idFile found, adding to uploadData');
          uploadData.idDocument = idFile;
        }
        if (addressFile) {
          $log.debug('addressFile found, adding to uploadData');
          uploadData.addressDocument = addressFile;
        }

        $log.debug('Upload data - ' + JSON.stringify(uploadData));

        $log.debug('Uploading data');

        var epochTicks = 621355968000000000;
        var ticksPerMillisecond = 10000;
        var yourTicks = epochTicks + ((new Date()).getTime() * ticksPerMillisecond);

        var boundary='---------------------------'+yourTicks;
        var header='--'+boundary+'\r\n';
        var footer='\r\n--'+boundary+'--\r\n';
        var contenttype='multipart/form-data; boundary='+boundary;

        var jsonContents=header+'Content-Disposition: form-data; name="customerInfoPart"\r\n';
        jsonContents+='Content-Type: application/json\r\n';
        jsonContents+='Content-Length: '+JSON.stringify(customerInfo).length+'\r\n\r\n';
        jsonContents+=JSON.stringify(customerInfo)+'\r\n';

        var idFileContents=header+'Content-Disposition: form-data; name="idDocument"; filename="'+$scope.idFile.name+'"\r\n';
        idFileContents+='Content-Transfer-Encoding: binary\r\n';
        idFileContents+='Content-Type: '+ $scope.idFile.type+'\r\n';
        idFileContents+='Content-Length: '+ $scope.idFile.size +'\r\n\r\n';

        var idFileReader = new FileReader();

        var addressFileContents=header+'Content-Disposition: form-data; name="addressDocument"; filename="'+$scope.addressFile.name+'"\r\n';
        addressFileContents+='Content-Transfer-Encoding: binary\r\n';
        addressFileContents+='Content-Type: '+$scope.addressFile.type+'\r\n';
        addressFileContents+='Content-Length: '+$scope.addressFile.size+'\r\n\r\n';

        var addressFileReader = new FileReader();

        var blob=new Blob([jsonContents,idFileReader.readAsArrayBuffer($scope.idFile),idFileReader,addressFileReader.readAsArrayBuffer($scope.addressFile),addressFileReader,footer]);

        $log.debug(blob.toString());

        $http.post(
          URLS.BASE + URLS.FILE_UPLOAD,
          blob,
          {'headers':{'Content-Type':contenttype}}
        ).success(function (data, status, headers, config) {
          // file is uploaded successfully
          usSpinnerService.stop('spinner');
          $log.debug('Upload Status - ' + status);

          $timeout(function () {
              $scope.serverMessage = data;
          });

          if (status===204) {
            $location.path('/signup-confirmation');
            SignupService.setCustomerSignupStatus(true);
          } 
        }).error(function (data, status, headers, config) {
          // handle error
          $log.debug('Signup failed with status ' + status);
          handleError(status);
        });
      };

      function handleError(error) {
          usSpinnerService.stop('spinner');
          scrollToServerMessage();
          $scope.serverMessage = 'Signup failed with status ' + error.status;
      }

      function scrollToServerMessage() {
          var old = $location.hash();
          $location.hash('serverMessage');
          $anchorScroll();
          //reset to old to keep any additional routing logic from kicking in
          $location.hash(old);
      }
    }
}());

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

Are MVC Controllers fundamental components in a Node.js application, or just another piece of the puzzle?

Currently, I am in the process of developing a web crawler using Node. This project aims to crawl through my different bank accounts and generate a quick summary of my financial situation. Although I am fully aware of the security concerns involved in this ...

Are there any comprehensive guides on AngularFire authentication and authorization techniques available?

If you're looking for help with AngularFire authentication, there are several useful resources to explore. For beginners, a good starting point is Basic user authentication with records in AngularFire. You may also find Anant Narayanan's presen ...

Exploring AngularJS: A Guide to Accessing Objects within Directives

I have successfully passed an object from the controller to the directive. However, when trying to access the object within the directive, it seems to be read as a string. Below is the code snippet, and I am trying to extract the City and State from the ...

What is the best method for aligning buttons in a row with all the other buttons?

I have been attempting to display two buttons, id="strength" and id="minion", when a certain button, id="expandButton", is clicked. I want these two buttons to be positioned on either side of the button that triggers their cre ...

Is there a reason why angularJS doesn't provide the exact error location directly, opting instead to just offer a link to their website that provides a generic explanation?

Why does AngularJS not provide the specific error location directly, such as which file the error is in, instead of just giving a link to their website with a generic explanation? This makes debugging very challenging! Whenever there is an error, it becom ...

How can I correctly export my npm package?

I have successfully developed an npm package. class Person { constructor() {} sayHello() {console.log("Hello World!")} } module.exports = Person; Upon installing the package using npm i my-package, it was integrated into my project. ...

Show only the portion of the image where the cursor is currently hovering

Information in advance: You can check out the current code or view the live demo (hover image functionality not included) at . The concept: I would like to have it so that when I hover my cursor (displayed as a black circle) over the image, only the s ...

Struggling to successfully toggle the visibility of items

I am currently facing an issue with displaying different sets of data based on button clicks. The first block of information is showing correctly upon page load, but when I try to display other blocks by clicking on the corresponding buttons, the info cont ...

Customizing the look of a div using CSS within an AngularJS directive

I am facing an issue with a directive I created that is using ng-repeat on an array of objects ---Displaying the values on the GUI------ Now, my goal is to have the background color of a particular div change when clicked. I attempted the following: li ...

Using Passportjs for user authentication with Angularjs (resource/http get)

I am currently experimenting with integrating Passportjs into an Angular and Express project. My current focus is on testing the Facebook strategy in passportjs. While authentication appears to be successful, I am encountering an issue where it does not n ...

There seems to be a problem with the text-to-speech API: It looks like there's a ReferenceError stating that

Currently, I am developing a program using the Quasar framework which is based on Vue and can be compiled for mobile using Cordova. However, I am encountering some issues when trying to run it on mobile. Below is the function causing problems: activat ...

Unit testing is encountering issues due to errors with objects not being accepted as a React child component

Here is the code where I am testing the functionality of mytestFunc when a checkbox is checked. Checkbox - <input id="mycheck" type="checkbox" onClick={this.mytestFunc} /> mytestFunc function - mytestFunc = e => { const mockdata = this.stat ...

Retrieve values from the query string (specifically from table rows and cells) for each individual line and display them in

i have some code, see: <script> $$.ready(function() { // Profile Dialog $( "#user-dialog" ).dialog({ autoOpen: false, modal: true, width: 400, open: function(){ $(this).parent().css('overflow', 'visible') ...

What is the best way to transfer item information from Flatlist within a React Native application?

I am a newcomer to react. In my App.js file, I have the main code, and in another folder, there is a lists.js file that contains the list data. I successfully import the list from lists.js into my App.js file. Now, I want to add an onPress action to the ...

error in Chrome app's webview extension

I have been working on a Chrome app using AngularJS 1.4. I am utilizing different tabs to navigate to various URLs and load them in a webview by using the webview.reload() function which sets its src attribute. For example: <div ng-init="view.init()"&g ...

In Vue.js2, you can easily compare two arrays of objects that have the same values and then make changes or add properties from one array to the other

I am working with an array of objects fetched from an API (), which is linked to a variable that serves as the v-model for an input. Whenever the variable changes, so does the array through a function that triggers the API call on @keyup. The structure of ...

JavaScript code to generate a UTF8 string from UTF codes

I am in possession of the byte representation of UTF8, such as: 195, 156 for "Ü" (capital U Umlaut) I am struggling to generate a JavaScript-compatible string from these numbers - all my attempts have been unsuccessful. Every method I have tried has mis ...

Tips for incorporating mapbox.js as a background while keeping html content and Navbar consistently displayed on top

I am currently integrating MapBox.js into a Bootstrap 3 website. The main concept is to utilize a map as the background for a row that occupies the full width of the site, with html-content displayed on top. To ensure MapBox.js remains in the background, I ...

Embed API requests using JavaScript's Axios library to ensure the correct promise is returned

I am currently facing an issue with posting data to my API using axios. In order to make the request, I need to include a XSFR-token along with it. The technologies I am using for this are React, Redux, Thunk, and Axios. The problem lies in handling this ...

Implementing the Delete feature using AJAX in this specific scenario: What is the best approach?

My website utilizes PHP, Smarty, MySQL, jQuery, and other technologies. It involves fetching a large amount of data from the database and presenting matching question ids on a webpage. This process of retrieving and displaying the matching question ids for ...