title: javascript: open file from byte array returned by json
body: <p>In javasript, I have a byte array and want to transform it back to the original fileType and open it. I have tried both with image/png and application/pdf but the result is the same. The file is damaged and can not be opened. Any suggestions on how to do this?</p>
  
  <p>Server side, my java code is like this:</p>
  
  <pre><code>...
  File downloadFile = myService.retriveMyFile(input);
  byte[] fileInBytes = new byte[(int)downloadFile.length()];
  InputStream inputStream = null;
  try {        
     inputStream = new FileInputStream(downloadFile);            
     inputStream.read(fileInBytes);            
  } finally {
     inputStream.close();
  }
  String json = new Gson().toJson(fileInBytes);
  response.setCharacterEncoding("UTF-8");
  response.getWriter().write(json);   
  </code></pre>
  
  <p>In javascript I try to open the file like this</p>
  
  <pre><code>...
  var a = document.createElement("a");
  document.body.appendChild(a);
  a.style = "display: none";
  var fileName = "test.png";
  xhr.onload = function () {
     if (xhr.status === 200) {
     var jsonResponse = xhr.response;
     var json = JSON.stringify(jsonResponse),
     blob = new Blob([json], {type: "image/png"}),
     url = window.URL.createObjectURL(blob);
     a.href = url;
     a.download = fileName;
     a.click();
     window.URL.revokeObjectURL(url);
  };
  </code></pre>