Back to topics

How to specify the download filename when using the browser's built-in PDF viewer

Usually, when downloading attachments, we set the filename via the download attribute of the a tag.

However, if you directly open a PDF link using window.open(), the page will be taken over by the browser's built-in PDF viewer.

This means that the filename of the download becomes uncontrollable.

Solution

Actually, you can specify the filename on the server side by setting response headers.
The key is:

'Content-Disposition': 'attachment; filename="example.pdf"'

// Note: This is server-side code for Next.js
export async function GET() {
  const url = "https:xxx.pdf";
  const response = await fetch(url);
  const blob = await response.blob();

  // Set the required response headers
  const headers = {
    "Content-Type": "application/pdf",
    "Content-Disposition": 'inline; filename="example.pdf"',
  };

  return new Response(blob, { headers });
}

Two Key Points

  1. About Content-Disposition

inline allows the browser to open and preview the PDF, while attachment triggers the browser's save-as dialog.

Content-Disposition: inline
Content-Disposition: attachment
Content-Disposition: attachment; filename="filename.jpg"

For more details, refer to MDN.

  1. About the Response object

An API that is rarely used on the frontend, but commonly used in server-side JavaScript.

new Response(body, init)

See https://developer.mozilla.org/zh-CN/docs/Web/API/Response/Response for details.