Home » Java » Saving binary data to file in javascript

Saving binary data to file in javascript

Posted by: admin June 30, 2018 Leave a comment

Questions:

Currently I can send my server an URL to file, then server saves that file to byte array and stores it in database. On demand, user can save that file.

It works fine for csv files (i have tested only those for now).

I’m having problems saving image files (png and jpeg).

Java code on getting file and saving it to byte array:

   ByteArrayOutputStream output = new ByteArrayOutputStream();
   InputStream inputStream = url.openStream(); //url of given file
   int n = 0;
   byte[] buffer = new byte[1024];

   while (-1 != (n = inputStream.read(buffer))) {
       output.write(buffer, 0, n);
   }

Part of my controller that sends back file through response:

    response.setBufferSize(8192);
    response.getOutputStream().write(file); //file is byte array

Javascript code for saving binary data to file and executing download:

    var textFileAsBlob = new Blob([data], {type: type}); //type is correct type (image/png, text/csv ...)
    var fileNameToSaveAs = name + '.' + extension; //Name of a file and correct extension
    var downloadLink = document.createElement("a");

IrfanView gives me decode error.

Answers: