Set the default save as name for a an <embed> or <iframe> that uses a Blob

Brian Deterling picture Brian Deterling · May 19, 2017 · Viewed 13.9k times · Source

I am generating a PDF in the browser using PDFKit (without node) and displaying it an iframe or an embed tag via the src attribute. The generated blob URL is some kind of UUID. So the overall page looks like:

<embed src="blob:http://localhost/eeaabb..."/>

The PDF appears fine, but when I click the Download link in Chrome, the default file name is the UUID. In FireFox, it is just "document.pdf".

If this were a server-generated PDF I would use Content-Disposition and/or manipulate the URL so the last part of it is the name I want, but that doesn't seem possible with a client-generated object.

Things I have tried:

  • Setting the PDF title via the metadata. This works but doesn't affect the filename.
  • Manipulating the embed tag title attribute. Doesn't seem to do anything.
  • Change the page title. Doesn't affect the file.
  • Try to append something to the data url. Just prevents the PDF from displaying.
  • Upload the PDF via POST, then download it via a page where I can control the URL. Could work, but seems crazy to generate a client-side PDF only to have to upload it to the server.

Is there any way around this so that I can control the default/suggested file name?

Answer

guest271314 picture guest271314 · May 19, 2017

Is there any way around this so that I can control the name?

No. You cannot control the name of a file stored at user local filesystem.

You can use <a> element with download attribute set to suggested file name. If user selects to download offered file user can change the file name at any time before or after downloading file.

window.onload = () => {
  let blob = new Blob(["file"], {
    type: "text/plain"
  });
  let url = URL.createObjectURL(blob);
  let a = document.createElement("a");
  a.href = url;
  a.download = "file.txt";
  document.body.appendChild(a);
  console.log(url);
  a.click();
}

At chrome, chromium browsers you can use requestFileSystem to store Blob, File or Directory at LocalFileSystem, which writes file to browser configuration directory, or other directories within user operating system. See