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

在JavaScript中,当你使用fetchaxios等库进行HTTP请求并希望直接获得一个Blob类型的数据时(例如处理图片、文件下载等场景),你可以通过配置请求来实现。下面是使用fetchaxios设置返回类型为Blob的示例。

使用fetch

async function fetchBlob(url) {
  try {
    const response = await fetch(url);
    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);
  }
}

// 使用示例
fetchBlob('https://example.com/somefile.jpg')
  .then(blob => {
    // 处理Blob对象,比如创建URL以便预览或下载
    const url = URL.createObjectURL(blob);
    console.log('Blob URL:', url);
  })
  .catch(error => console.error(error));

使用axios

首先,确保你已经安装了axios库。如果还没有安装,可以通过npm或yarn来安装:

npm install axios
# 或者
yarn add axios

然后,可以这样设置返回类型为Blob

const axios = require('axios');

async function axiosGetBlob(url) {
  try {
    const response = await axios.get(url, { responseType: 'blob' });
    return response.data; // 这里直接返回的就是Blob对象
  } catch (error) {
    console.error('There was a problem with the axios request:', error);
  }
}

// 使用示例
axiosGetBlob('https://example.com/somefile.jpg')
  .then(blob => {
    // 处理Blob对象,比如创建URL以便预览或下载
    const url = URL.createObjectURL(blob);
    console.log('Blob URL:', url);
  })
  .catch(error => console.error(error));

在这两个示例中,我们都是先发起一个GET请求到指定的URL,然后通过配置确保响应体被处理为Blob类型。这样就可以方便地处理二进制数据,如图片、文档的下载或预览了。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值