簡體   English   中英

有沒有一種通過下載鏈接獲取文件 mime 類型/擴展名的好方法?

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

我需要從下載鏈接獲取文件擴展名,目前我正在使用以下腳本(摘自 React 鈎子)

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

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

這段代碼有效,但問題是response.blob()相對於文件大小需要時間,我想我的解決方案很糟糕。

也許有一些優雅的方法來解決我的問題?

我的錯,剛剛發現我有我需要的所有標題,我對headers道具感到困惑:

在此處輸入圖像描述

原來它不是空的,我可以通過以下代碼獲取我的 mime 類型:

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

另外,我認為HEAD在這里很合適

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM