2

I am getting base64 data from an end point and need to display the file in a new tab. How do I set the file name in window.open?. Is it even possible?

import React from "react";

export function convertDataToBinary(base64Data) {
  // win.atob === raw char
  const raw = window.atob(base64Data);
  // arr[unit_8][buffer]
  const array = new Uint8Array(new ArrayBuffer(raw.length));

  // arr[0]['a']
  // arr[1]['b']
  for (let i = 0; i < raw.length; i++) {
    array[i] = raw.charCodeAt(i);
  }

  // re
  return array;
}

// return blob
export function convertDataToBlob(data, mimeType) {
  // 1. data === base64
  // 2. mineType === application/pdf
  const arr = convertDataToBinary(data);
  // blob([2d_arr], mime_type)
  return new Blob([arr], {type: mimeType});
}

function openInNewTab(url) {
  let win = window.open(url, '_blank');
  win.focus();
}

function App() {


  const file = require('./file.json');
  const mimeType = 'application/pdf'; // proper
  const data = convertDataToBlob(file.data, mimeType);

  const url = window.URL.createObjectURL(data);

  return <div className="App">
    <div onClick={() => {openInNewTab(url)}}>Something To Click On</div>
  </div>;
}

export default App;

Full code: https://github.com/kenpeter/new-tab-doc

kenpeter
  • 7,404
  • 14
  • 64
  • 95
  • You say you have to "display the file in a new tab", what kind of file is it that the browser is able to display it? The question linked by @Cerbrus was willing to "download" that resource, is it ok with your case? If fast-read correctly your code, that would be a pdf file, is that right? In this case, your question would rather be [a duplicate of this one](https://stackoverflow.com/questions/53548182/can-i-set-the-filename-of-a-pdf-object-displayed-in-chrome/53593453#53593453). – Kaiido Oct 15 '19 at 06:53
  • @Kaiido, yes saw the answer you made. It is good. Currently, I want to display (not download) PDF, JPG, PNG and other standard images in new tab, in IE11, Chrome, Firefox. Other file types should be open new tab, then download. – kenpeter Oct 15 '19 at 12:42

0 Answers0