Renaming Downloaded Files

In this example, the modification of the Content-Disposition in the response headers achieves the modification of the downloaded file name according to the fileName parameter in the request URL.

Sample Code

async function handleRequest(request) {
  const url = new URL(request.url);
  const fileName = url.searchParams.get('fileName');

  const response = await fetch(request);

  // Evaluate the response status code and the search parameter
  if (response.status !== 200 || !fileName) {
    return response;
  }

  // Modify the Content-Disposition response header
  response.headers.append('Content-Disposition', `attachment; filename="${fileName}"`);
  return response;
}

addEventListener('fetch', event => {
  event.passThroughOnException();
  event.respondWith(handleRequest(event.request));
});

Sample Preview

Enter a URL (such as https://example.com/origin.exe?fileName=modified.exe) that matches the trigger rule of Edge Function in the address bar of the browser on both the PC and mobile terminal to preview the example effect.

xx1.png

Related References

  1. Runtime APIs: Fetch
  2. Runtime APIs: Response