当使用fetch
或axios
发出带有参数的GET请求并希望将响应类型设置为Blob
时,可以在请求配置中添加查询参数以及指定响应类型。以下是两个库的具体示例:
使用fetch带参数
async function fetchBlobWithParams(url, params) {
const queryString = Object.keys(params)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
.join('&');
const fullUrl = `${url}?${queryString}`;
try {
const response = await fetch(fullUrl);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const blob = await response.blob();
return blob;
} catch (error) {
console.error('There was a problem with the fetch operation:', error);
}
}
// 使用示例
const params = { id: 123, type: 'image' };
fetchBlobWithParams('https://example.com/somefile', params)
.then(blob => {
const url = URL.createObjectURL(blob);
console.log('Blob URL:', url);
})
.catch(error => console.error(error));
使用axios带参数
const axios = require('axios');
async function axiosGetBlobWithParams(url, params) {
try {
const response = await axios.get(url, {
params,
responseType: 'blob',
});
return response.data; // Blob对象
} catch (error) {
console.error('There was a problem with the axios request:', error);
}
}
// 使用示例
const queryParams = { postId: 456, format: 'pdf' };
axiosGetBlobWithParams('https://example.com/files', queryParams)
.then(blob => {
const url = URL.createObjectURL(blob);
console.log('Blob URL:', url);
})
.catch(error => console.error(error));
在这两个示例中,我们向请求URL添加了查询参数,并保持了将响应体处理为Blob
类型的能力。这样,你就可以根据需要传递参数,并处理返回的二进制数据了。