当前位置:   article > 正文

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

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));
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

使用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));
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

在这两个示例中,我们向请求URL添加了查询参数,并保持了将响应体处理为Blob类型的能力。这样,你就可以根据需要传递参数,并处理返回的二进制数据了。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/615270
推荐阅读
相关标签
  

闽ICP备14008679号