You say you want the binary content of the file to be sent via JSON and storage in mongoDB. The problem with your code is that you read the file as text, when you have to read it as an ArrayBuffer , which will not apply text encoding to binary values.
ArrayBuffer great, but not all browsers will support sending ArrayBuffer via JSON via XMLHttpRequest . Especially if you know the format it should be in, it might be a good idea to convert it to a regular array. Fortunately, we can use typed arrays in JavaScript to help with this.
var myapp = angular.module('myapp', []); myapp.controller('MainCtrl', function ($scope) { $scope.showContent = function($fileContent) { $scope.content = $fileContent; }; }); myapp.directive('onReadFile', function ($parse) { return { restrict: 'A', scope: false, link: function(scope, element, attrs) { var fn = $parse(attrs.onReadFile); element.on('change', function(onChangeEvent) { var reader = new FileReader(); reader.onload = function(onLoadEvent) { var buffer = onLoadEvent.target.result; var uint8 = new Uint8Array(buffer);
Updated script: https://jsfiddle.net/6aG4x/796/
source share