await get 请求带参数设置返回类型为blob

当使用fetchaxios发出带有参数的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类型的能力。这样,你就可以根据需要传递参数,并处理返回的二进制数据了。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值