如何用typescript将Axios的响应数据转换为`Blob`

问题描述 投票:0回答:1

我让这段代码在 axios“^0.25.0”上运行,但在构建响应数据的

Blob
时在“^0.28”上出现错误。

代码:

<--- more codes -->
    return new Promise(async (resolve, reject) => {
      try {
        const response = await axios({
          url: result?.source_file,
          method: "GET",
          responseType: "blob",
        });
        const blob = new Blob([response.data], { type: "audio/mp3" });
        const buffer = await blob.arrayBuffer();
        const item: ResultFile = {
          audioFileId: audioFile.id,
          type: type,
          buffer: buffer,
          blobType: blob.type,
        };
        db.resultFiles.add(item);
        resolve(blob);
      } catch (error) {
        this.log.error(error);
        reject(error);
      }
    });

错误:

    Type 'AxiosResponse<any, any>' is not assignable to type 'BlobPart'.ts(2322)
const response: AxiosResponse<AxiosResponse<any, any>, any>

我尝试过分配通用的

axios<Blob>
,但它似乎不起作用。有什么指点吗?

typescript audio axios blob
1个回答
0
投票

尝试解析 Promise 的 try-catch 中的 blob 并检查

.then(blob)
是否返回您期望的 blob。

这是使用相同

responseType
选项获取图像的示例。

const promise: Promise<Blob> = new Promise(async (resolve, reject) => {
        try {
            const response = await axios.get('https://dummyjson.com/image/150', {
                responseType: 'blob',
            })
            const blob = new Blob([response.data], { type: 'image/jpeg' })
            resolve(blob)
        } catch (error) {
            console.log('error: ', error)
            reject(error)
        }
    })
    
promise.then((blob) => {
    // handle the setter here to take the blob value
    console.log(blob)
})
© www.soinside.com 2019 - 2024. All rights reserved.