1

My website is called www.example.com, and I keep my files in a storage bucket called storage.example.com.

Each file has a hash-like filename in the bucket (to prevent scrapers), but I would like to rename this to something sensible when a user clicks the download link from www.example.com.

In the old days, you used to be able to use the download attribute within <a>, however, the MDN docs say that this only works for same-origin URLs, and storage.example.com is considered to be different. This means that download attribute is ignored, and the default hash-like filename is used.

Is there an easy way to do this in 2022? Many answers like this are written before modern browsers started blocking the desired behavior. I understand that it seems like I am trying to bypass a security feature, so I am also open to suggestions that achieve the same outcome while not compromising security.

Note: the files are small zip files (~30kB), so a solution that downloads, renames then presents the result to the user would work.

Anjum Sayed
  • 872
  • 9
  • 20
  • 1
    The only way that I'm aware of to successfully do this cross-domain would be to have `storage.example.com` send an appropriate `Content-Disposition` header in its response to the resulting request, a la `Content-Disposition: attachment; filename="filename.jpg"`. – esqew Dec 16 '22 at 16:12
  • "*Each file has a hash-like filename in the bucket (to prevent scrapers)*" Are these publicly-accessible files, or are they supposed to only be accessed by specific users? If the former - why do you care about scrapers? For the latter - sounds like you're missing a critical piece of an authorization flow here - what you have proposed is not particularly effective security. – esqew Dec 16 '22 at 16:14
  • @esqew Yes these are publicly accessible files, but the link is served via an authenticated API. The reason the filename is a hash is to make it difficult to do a bulk scrape of these files directly from the storage bucket – Anjum Sayed Dec 16 '22 at 16:17
  • 1
    Could you fetch() the file into a blob and then create a local url for download? https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API https://stackoverflow.com/questions/25547475/save-to-local-file-from-blob https://stackoverflow.com/questions/13405129/create-and-save-a-file-with-javascript – This Guy Dec 16 '22 at 16:25

1 Answers1

0

The option suggested by esqew in the comments above seems to be the best solution for my problem. If the files are kept in a Google Storage Bucket, you can edit the metadata of a blob and set the Content-Disposition field:

enter image description here

This adds an additional step when new files are added but I automated this using a Python script

I also tried This Guy's suggestion by saving to a blob using FileSaver.js, however it has the undesired effect of setting off the pop-up blocker in the current version of Chrome

Anjum Sayed
  • 872
  • 9
  • 20