简体   繁体   English

有没有一种通过下载链接获取文件 mime 类型/扩展名的好方法?

[英]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)我需要从下载链接获取文件扩展名,目前我正在使用以下脚本(摘自 React 钩子)

// ...
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.这段代码有效,但问题是response.blob()相对于文件大小需要时间,我想我的解决方案很糟糕。

Maybe there is some elegant way to solve my problem?也许有一些优雅的方法来解决我的问题?

My bad, just discovered that I have all the headers I need, I was confused with empty headers prop:我的错,刚刚发现我有我需要的所有标题,我对headers道具感到困惑:

在此处输入图像描述

Turns out it's not empty and I can get my mime type by this code:原来它不是空的,我可以通过以下代码获取我的 mime 类型:

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

Also, I think HEAD is appropriate here另外,我认为HEAD在这里很合适

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM