72G*_*2GM 2 download reactjs react-query
Using fetch I can create a download link by doing the following code
const result = await fetch(authLinkProps.url, {
headers: {
Authorization: getUserToken(),
},
});
const blob = await result.blob();
const href = window.URL.createObjectURL(blob);
Run Code Online (Sandbox Code Playgroud)
All works fine but I'm using React Query for my project so I want to be consistent and use this to do the same thing.
If I do the following
const { data, error } = useDocuments(authLinkProps.url);
let href: string = '';
console.log(data);
if (data !== undefined) {
href = window.URL.createObjectURL(data);
}
Run Code Online (Sandbox Code Playgroud)
Where useDocuments is
return useQuery<Blob, Error>('document-download', async () => {
const dwnldHeader = {
headers: {
Authorization: currentUser,
responseType: 'blob',
},
};
const { data } = await axios.get<Blob>(apiUrl, dwnldHeader);
return data;
});
Run Code Online (Sandbox Code Playgroud)
I get the error
"Uncaught (in promise) TypeError: Failed to execute 'createObjectURL' on 'URL': Overload resolution failed."
Run Code Online (Sandbox Code Playgroud)
Data looks like a blob if I console it out?
Any ideas?
小智 5
useQuery似乎将 blob 响应转换为字符串。对我有用的是使用 arraybuffer 返回类型,然后将其转换为 blob。
此外,它responseType不是标头对象的一部分,而是配置的一部分。
在你的情况下 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);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6199 次 |
| 最近记录: |