How to set the name of a blob file in JavaScript when force downloading it through window.location?

Spread the love

Sometimes, we want to set the name of a blob file in JavaScript when force downloading it through window.location.

In this article, we’ll look at how to set the name of a blob file in JavaScript when force downloading it through window.location.

How to set the name of a blob file in JavaScript when force downloading it through window.location?

To set the name of a blob file in JavaScript when force downloading it through window.location, we set the 2nd argument of the File constructor to the file name.

For instance, we write

const file = new File([json], fileName, { type: "application/json" });
const exportUrl = URL.createObjectURL(file);
window.location.assign(exportUrl);
URL.revokeObjectURL(exportUrl);

to create a File object.

The 2nd argument is the string with the file name.

We convert the file to a base64 URL string with URL.createObjectURL.

Then we call window.location.assign with the file object converted to a base64 URL to download the file.

Conclusion

To set the name of a blob file in JavaScript when force downloading it through window.location, we set the 2nd argument of the File constructor to the file name.

Leave a Reply

Your email address will not be published.