Explain Codes LogoExplain Codes Logo

How to set the name of a file downloaded from a browser?

javascript
blob
file-download
javascript-techniques
Anton ShumikhinbyAnton Shumikhin·Jan 15, 2025
TLDR

To control the download filename, use Content-Disposition header with attachment; filename="name.ext".

Here's a quick example:

<a href="path/to/file" download="name.ext">Download</a>

For server-side controls, like PHP:

<?php header('Content-Disposition: attachment; filename="name.ext"'); ?>

HTML's download attribute names files on-the-fly, but server-side ensures browser compatibility.

To improve communication with users, the download attribute or Content-Disposition header influences desired filenames.

Name that blob: JavaScript downloads

JavaScript allows for custom file download solutions. The method URL.createObjectURL() paired with Blob objects can be used to also control the download's filename:

// Yeah! You're about to become a Blob Whisperer. Just like Harry Potter, but with Blobs, not snakes. const data = new Blob([content], {type: 'text/plain'}); const url = window.URL.createObjectURL(data); const a = document.createElement('a'); a.style.display = 'none'; // Playing hide and seek with anchor tag (Spoiler: We always win!) a.href = url; a.download = 'customName.txt'; // Like "Tom Riddle" into "Voldemort", just less evil. // Time for some magic! Abracadabra! document.body.appendChild(a); a.click(); // Obliviate! (Well, just to revoke the URL, nothing else!) setTimeout(() => { document.body.removeChild(a); window.URL.revokeObjectURL(url); }, 0);

You call it Visualization. We call it magic.

Visualizing the filename assignment for a download is a fascinating process akin to sorting Hogwarts students into houses:

When you click to download: You -> [Sits on the sorting stool and says 🔗] Behind the scenes: Browser -> [Sorting hat says: "Unnamed File!"] With the 'Content-Disposition' header: Browser -> [Sorting hat says: "**Desired Filename**" instead] Final step: Downloaded 📁: **Desired Filename**

The "Content-Disposition" header is a Dumbledore in the world of downloads.

Serve it right: Server-Side vs Client-Side filename declaration

Choosing between server-side and client-side filename control might feel like choosing between Slytherin and Gryffindor, but the decision mainly depends on the scenario:

Server-side solution:

  • A good solution for cross-browser compatibility concerns.
  • Appropriate for sensitive files which should not be delivered via JavaScript.
  • Can be employed when you want to straddle file transmission with server-side logging or analytics mechanisms.

Client-side solution:

  • Handy with dynamically generated content within the browser.
  • Leverages user's device resources, potentially saving server resources.
  • Ideal for offline apps where server interaction is absent.

Ye olde MIME types

Proper MIME types in response headers ensure accurate handling of a file by browsers. A misconfigured type might display the file instead of initiating download. Content-Disposition header with application/octet-stream MIME type forces a download.

Here's how to force a download in PHP:

<?php header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="example.ext"'); ?>

In JavaScript, set MIME type when creating the Blob:

// Drumroll, please. Presenting the Blob constructor! const data = new Blob([content], {type: 'mime/type'});

DOM Cleaning: Not your random Spring Cleaning

It's crucial to keep your DOM tidy post-download by deleting any elements utilized for the download. This clean-up check is a simple act of being a good web-citizenship. It's like picking up after your pet—an essential part of responsible Blob ownership:

setTimeout(() => { // Thank you for your service, URL! You're relieved now. You deserve a vacation! document.body.removeChild(a); window.URL.revokeObjectURL(url); }, 0);