【问题标题】:Download Blob with React Query, createObjectURL error使用 React Query 下载 Blob,createObjectURL 错误
【发布时间】:2022-10-07 23:07:48
【问题描述】:

使用 fetch 我可以通过执行以下代码来创建下载链接

const result = await fetch(authLinkProps.url, {
      headers: {
        Authorization: getUserToken(),
      },
    });

    const blob = await result.blob();
    const href = window.URL.createObjectURL(blob);

一切正常,但我在我的项目中使用 React Query,所以我希望保持一致并使用它来做同样的事情。

如果我执行以下操作

const { data, error } = useDocuments(authLinkProps.url);
let href: string = '';
console.log(data);
if (data !== undefined) {
    href = window.URL.createObjectURL(data);
}

useDocuments 在哪里

return useQuery<Blob, Error>('document-download', async () => {
    const dwnldHeader = {
      headers: {
        Authorization: currentUser,
        responseType: 'blob',
      },
    };
    const { data } = await axios.get<Blob>(apiUrl, dwnldHeader);
    return data;
  });

我得到错误

"Uncaught (in promise) TypeError: Failed to execute 'createObjectURL' on 'URL': Overload resolution failed."

如果我将其控制出来,数据看起来像一团?

有任何想法吗?

【问题讨论】:

    标签: reactjs download react-query


    【解决方案1】:

    useQuery 似乎将 blob 响应转换为字符串。对我有用的是使用 arraybuffer 返回类型,然后将其转换为 blob。

    此外,responseType 不是 headers 对象的一部分,而是配置的一部分。

    在您的情况下,对于 useDocuments

    return useQuery<Blob, Error>('document-download', async (apiUrl) => {
      const config = {
        headers: {
          Authorization: currentUser,
        },
        responseType: 'blob',
      };
      const { data } = await axios.get(apiUrl, config);
      return new Blob(data);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 2022-10-24
      • 1970-01-01
      • 2016-04-16
      • 2018-12-10
      • 2022-10-26
      • 1970-01-01
      相关资源
      最近更新 更多