Коксик
Коксик

Reputation: 63

Is there a fine way to get file mime type / extension by a download link?

I need to get file extension from a download link, currently I'm using the following script (excerpt from React hook)

// ...
useEffect(() => {
    /// ...
    void (async () => {
      try {
        setIsLoading(true);
        const response = await fetch(downloadLink);
        const blob = await response.blob();

        setFileExtension(fileExtensionByMimeType[blob.type]);
      } finally {
        setIsLoading(false);
      }
    })();
  }, []);
// ....

This code works, but the problem is that response.blob() takes time relatively to the file size, and I guess my solution is just bad.

Maybe there is some elegant way to solve my problem?

Upvotes: 1

Views: 2771

Answers (1)

Коксик
Коксик

Reputation: 63

My bad, just discovered that I have all the headers I need, I was confused with empty headers prop:

enter image description here

Turns out it's not empty and I can get my mime type by this code:

const response = await fetch(downloadLink, { method: 'HEAD' });
const mimeType = response.headers.get('content-type');

Also, I think HEAD is appropriate here

Upvotes: 2

Related Questions