3

I am trying to upload files in JSON using angular and FileReader Api.

The problem is that for files larger than 600 - 700 KB my browser crashes.

As far as I can see the problem occurs when requesting against a resource and not when the file reader reads the file and encode that in base64

Any ideas?

Here is the code:

function readFiles(files) {

  var reader = new FileReader();
  var data = [];

  function readFile(index) {

    if (index >= files.length) {

     UploadFilesResource.create(JSON.stringify(data), function  (successData) {
       scope.attachments = successData.data;
       scope.showUploadForm = false;
     }, function (errorData) {
       MessageSrv.setErrorMessage(errorData.error_message)
     });

     return;
  }

  var file = files[index];

  reader.onload = function(e) {
     data.push(prepareFile(file, e.target.result));
     readFile(index + 1)
   };

   reader.readAsDataURL(file);
  }

  readFile(0);
}

And here is the Resource Code:

crmApp.lazy.factory('UploadFilesResource',
['CrmAppResource', 'CrmAppConfiguration',
    function ($resource, CrmAppConfiguration) {
        return $resource(
            CrmAppConfiguration.apiUrl + 'upload/files/:id',{id:'@id'}
        );
    }
]);
Abhishek
  • 1,477
  • 1
  • 10
  • 18
ibekiaris
  • 31
  • 4
  • If it works with smaller file size, the problem is most probably on the backend. Can you also post the backend code? – Jagrut Mar 14 '17 at 10:19
  • 2
    Why would the browser crash if the problem is on the backend? I think the problem is JSON.stringify – Jonas Grumann Mar 14 '17 at 10:21
  • There is no backend implementation at the moment. Only a dummy rest endpoint just for testing. As for the backend is a simple apache installation (default config) for a PHP 5.5.9 project using also ZF2. For the moment the problem occurs on local environment. – ibekiaris Mar 14 '17 at 10:23
  • So, `data` is an array of strings, each 700k - 800k characters long? And you're wondering why the browser hangs stringifying that? :) Dude, that's massive. Just post your base64 data one at a time, and don't stringify anything. – Jeremy Thille Mar 14 '17 at 10:38
  • Thank you @JeremyThille. I ll try not to stringify. I ll try that by the end of this day. However the problem occurs trying to upload just one file. – ibekiaris Mar 14 '17 at 10:45
  • 2
    Yes, because even one 700k long string is _big_. Try to open a text editor and type _seven hundred thousand_ letters, and you'll understand what you're putting the browser through. – Jeremy Thille Mar 14 '17 at 11:07

1 Answers1

0

Thank you @Jeremy and @Jonas

That worked! The problem was JSON.stringify

So I removed that and now everything is OK with the browser!

ibekiaris
  • 31
  • 4