getHttpBlob【获取远程二进制数据流】
描述
通过 ajax 获取远程二进制数据流
# 1.示例
复制代码
# 2.入参说明
| 参数 | 说明 | 类型 | 是否必填 | 默认值 |
|---|---|---|---|---|
| url | http 链接地址 | String | 是 | |
| options | 选项 | object | 否 | {} |
# 2.1 options 入参说明
| 参数 | 说明 | 类型 | 是否必填 | 默认值 |
|---|---|---|---|---|
| method | 请求方式,可选值:GET、POST、DELETE、PUT | String | 是 | GET |
| headers | 请求头 | object 、undefined | 否 | undefined |
| data | 请求实体 | object、undefined | 否 | undefined |
# 3.源码
源码,点开查看 👈
import isPlainObject from '@/base/isPlainObject'
/**
* ajax根据http链接地址 获取远程blob
* @param {string} url
* @param {{method?: string, data: object, headers: object }} option
* @returns {Promise<unknown>}
*/
function getHttpBlob(url, option = {}) {
const defaultOpts = {
method: 'GET',
data: undefined,
headers: undefined,
...option
}
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open(defaultOpts.method?.toUpperCase?.(), url, true)
xhr.responseType = 'blob'
// xhr.setRequestHeader('Content-Type', 'application/json')
if (isPlainObject(defaultOpts.header)) {
Object.entries(defaultOpts.header).forEach(([k, v]) => {
xhr.setRequestHeader(k, v)
})
}
xhr.send(JSON.stringify(option.data))
xhr.onload = () => {
if (xhr.status === 200) {
resolve(xhr.response)
} else {
reject(xhr)
}
}
})
}
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
27
28
29
30
31
32
33
34
35
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
27
28
29
30
31
32
33
34
35
上次更新: 2025/07/01, 14:52:29