question

Upvotes
Accepted
1 1 1 2

How to create File object in AngularJS ?

In javascript it is very simple to create file object just like that :

var assetLocalPath="C:/Users/Pictures/flower..jpg";

var file = new File([""],assetLocalPath);

alert(file);

It will alert [object File]

Same as above I would like to create in AngularJS, but I am getting an error " TypeError: File constructor cannot be called in nwdisabled frame "

Please suggest.

javascript
icon clock
10 |1500

Up to 2 attachments (including images) can be used with a maximum of 5.0 MiB each and 10.0 MiB total.

Upvotes
Accepted
11.5k 16 7 10

Hello @naiyar88

Is you AngularJS question related to any Thomson Reuters APIs/Products? If it is related to the pure AngularJS, I suggest you post the question in Angular JS community or Stack Overflow which are more appropiete place.

icon clock
10 |1500

Up to 2 attachments (including images) can be used with a maximum of 5.0 MiB each and 10.0 MiB total.

Upvotes
14 0 0 4

Hi Naiyar88,

Are you trying to upload a file?

Use <input type="file">

I'm currently using angular-material-fileinput so the code looks a bit different but it does use <input type="file"> under the hood so I think you can figure it out:

// upload.html
// left out code for brevity
 <lf-ng-md-file-input lf-files="vm.filesToUpload"> </lf-ng-md-file-input>

// upload.controller.js
// left out code for brevity
(function() {

  "use strict";

  angular.module('Contracts').controller('UploadController', UploadController);

  UploadController.$inject = [
    'FileProviderService',
  ];
  function UploadController(FileProviderService) {
    var vm = this;

    vm.filesToUpload = [];
    vm.submit = submit;

    function submit() {
      FileProviderService.uploadFile(vm.filesToUpload, function(response) {
          // do stuff if success
        },
        function error(err) {
          // do stuff if error
        })
    }

  }

})();
// file-provider.service.js
// left out code for brevity
(function() {

  "use strict";

  angular.module('Services').factory("FileProviderService", FileProviderService);

  FileProviderService.$inject = [
    '$resource',
    'ENV_VARS'
  ];

  function FileProviderService($resource, ENV_VARS) {
    var url = ENV_VARS.FILE_PROVIDER_SERVICE_URL;
    var Resource = $resource(url, {}, {

      uploadFile: {
        method: 'POST',
        url: url + '/path',
        headers: {
          'Content-Type': undefined
        },
        transformRequest: function(data) {
          var formData = new FormData();
          angular.forEach(data, function(fileObj, index, files) {
            formData.append("filesToUpload", fileObj.lfFile);
          });
          return formData;
        }
      }
      // ******************************************* //
      // more file provider methods defined down here
      // ******************************************* //
    });

    return Resource;
  }

})();

Thank you

icon clock
10 |1500

Up to 2 attachments (including images) can be used with a maximum of 5.0 MiB each and 10.0 MiB total.

Upvotes
1 0 0 0

First we write the directive to gain access to the file object in our controller. In the snippet below, file-model is an attribute on a file input element, and its value is the name of the variable in our controller’s scope that binds to the file object.

.directive('fileModel', ['$parse', function ($parse) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var model = $parse(attrs.fileModel);
            var modelSetter = model.assign;

            element.bind('change', function(){
                scope.$apply(function(){
                    modelSetter(scope, element[0].files[0]);
                });
            });
        }
    };
}]);

In the link function of the above directive, we listen for changes to the content of the input element and change the value of the variable in the scope accordingly. This is achieved using the $parse service to set the value in our scope. The markup required in the view for the directive to work is simple:

<input type="file" file-model="myFile"/>

icon clock
10 |1500

Up to 2 attachments (including images) can be used with a maximum of 5.0 MiB each and 10.0 MiB total.

Upvotes
1 0 0 0

To have the file upload input handle the selection change event, what I had to do is use angular.element() to query the hidden file upload input and assign an event-handling method to it:

angular.element("#fileUploadField").bind("change", function(evt) { if (evt) { ... } });

Also, follow us https://www.codeproject.com/Articles/5163873/Upload-File-with-AngularJS-using-ngResource



icon clock
10 |1500

Up to 2 attachments (including images) can be used with a maximum of 5.0 MiB each and 10.0 MiB total.

Upvotes
1 0 0 0

There is an input control available in HTML that does this. I know. What I need is not this predefined input control. What I need is a readonly text field, and a button grouped together. The button can be clicked and pops up the File Open dialog so it can be used to select a file. The text field will display the file name. With Bootstrap, this is very easy to define:

<div class="input-group">

<input type="file" id="fileUploadField" style="display: none;">

<input type="text" id="fileNameDisplayField" class="form-control"


ng-model="vm.uploadFileName" placeholder="File to Upload" readonly="readonly">

<div class="input-group-addon btn btn-default"


ng-click="vm.clickSelectFile()"><i class="glyphicon glyphicon-file"></i></div>

</div>

In the code snippet above, there are some attributes specific for AngularJS. You can ignore these for now. The outer <div> element has CSS class "input-group". It can smash multiple input control into one. With the above code snippet, it will create an input control


icon clock
10 |1500

Up to 2 attachments (including images) can be used with a maximum of 5.0 MiB each and 10.0 MiB total.

Upvotes
1 0 0 0

Hi,

Creating the AngularJS File, have a look -


// export page definition to json file   
 $scope.exportToFile = function()
{        
var filename = 'filename'               
var blob = new Blob([angular.toJson(object, true)], {type: 'text/plain'});        
if (window.navigator && window.navigator.msSaveOrOpenBlob) 
{            
window.navigator.msSaveOrOpenBlob(blob, filename);       
 }
 else
{            
var e = document.createEvent('MouseEvents'),           
 a = document.createElement('a');            
a.download = filename;         
   a.href = window.URL.createObjectURL(blob);            
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');        
    e.initEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);          
  a.dispatchEvent(e);          
  // window.URL.revokeObjectURL(a.href); // clean the url.createObjectURL resource        } 
   }
icon clock
10 |1500

Up to 2 attachments (including images) can be used with a maximum of 5.0 MiB each and 10.0 MiB total.

Click below to post an Idea Post Idea