Home > Web Front-end > JS Tutorial > How Can I Force a Specific Filename When Downloading a Blob File in JavaScript?

How Can I Force a Specific Filename When Downloading a Blob File in JavaScript?

Susan Sarandon
Release: 2024-12-14 08:00:19
Original
303 people have browsed it

How Can I Force a Specific Filename When Downloading a Blob File in JavaScript?

Setting Blob File Name for Forced Downloads in JavaScript

When downloading a blob file directly through window.location, the default filename is a random string. However, you may want to set a custom filename to make it more informative.

To achieve this, you can't rely solely on the window.location method. Instead, you'll need to use the following steps:

  1. Create a hidden element.
  2. Set its href attribute to the blob's URL.
  3. Set its download attribute to the desired filename.
  4. Trigger a click on the element.

Here's an example that simplifies the process:

const saveData = (function () {
  const a = document.createElement("a");
  document.body.appendChild(a);
  a.style = "display: none";
  return (data, fileName) => {
    const json = JSON.stringify(data);
    const blob = new Blob([json], { type: "octet/stream" });
    const url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = fileName;
    a.click();
    window.URL.revokeObjectURL(url);
  };
})();

const data = { x: 42, s: "hello, world", d: new Date() };
const fileName = "my-download.json";

saveData(data, fileName);
Copy after login

Notes:

  • Older browsers may not support the download attribute.
  • Certain file formats may be restricted by the browser, causing download failures. Consider using a different file extension (.txt for JSON, for example).

The above is the detailed content of How Can I Force a Specific Filename When Downloading a Blob File in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template