一个接口根据不同的情况返回不同的数据类型,有时返回excel文件,需要前端下载,有时返回json,前端如何处理

发布于:2022-11-28 ⋅ 阅读:(658) ⋅ 点赞:(0)

很多开发者可能用过Blob,但是却并没有认真了解过Blob是什么?Blob的API有哪些?我们什么时候会用到Blob?

下面跟我一起详细了解下Blob吧~

一、Blob 是什么

Blob(Binary Large Object)表示二进制类型的大对象。在数据库管理系统中,将二进制数据存储为一个单一个体的集合。Blob 通常是影像、声音或多媒体文件。在 JavaScript 中 Blob 类型的对象表示不可变的类似文件对象的原始数据。 为了更直观的感受 Blob 对象,我们先来使用 Blob 构造函数,创建一个 myBlob 对象,具体如下图所示:

如你所见,myBlob 对象含有两个属性:size 和 type。其中 size 属性用于表示数据的大小(以字节为单位),type 是 MIME 类型的字符串。Blob 表示的不一定是 JavaScript 原生格式的数据。比如 File 接口基于 Blob,继承了 blob 的功能并将其扩展使其支持用户系统上的文件。·
 

2.2 属性

前面我们已经知道 Blob 对象包含两个属性:·

    size(只读):表示 Blob 对象中所包含数据的大小(以字节为单位)。
    type(只读):一个字符串,表明该 Blob 对象所包含数据的 MIME 类型。如果类型未知,则该值为空字符串。

2.3 方法

    slice([start[, end[, contentType]]]):返回一个新的 Blob 对象,包含了源 Blob 对象中指定范围内的数据。
    stream():返回一个能读取 blob 内容的 ReadableStream。
    text():返回一个 Promise 对象且包含 blob 所有内容的 UTF-8 格式的 USVString。
    arrayBuffer():返回一个 Promise 对象且包含 blob 所有内容的二进制格式的 ArrayBuffer。


responseType: 'blob'

  userSearch: (data) => common({ url: urls.light.userSearch, data, method: 'post', responseType: 'blob', allResponse: true }),

 

 Blob格式转json格式,方法一:

    Api.light
      .userSearch({ pageNum: page, pageSize, ...searchParams })
      .then((res) => {
        const file = new FileReader() //读取文件
        file.readAsText(res.data, 'utf-8') //读取文件,并设置编码格式为utf-8
        file.onload = function () {
          //在读取文件操作完成后触发
          const message = JSON.parse(file.result) //reader.result返回文件的内容,只在读取操作完成后有效
          return message //此时message为转化好的json格式
        }
        if (res.code === 200) {
          setState({
            dataSource: res.data.list,
            pageSize: res.data.pageSize,
          })
          setTotal(res.data.total)
          setCurrent(res.data.pageNum)
        }
      })

 Blob格式转json格式,方法二:

   Api.light
      .userSearch({ pageNum: page, pageSize, ...searchParams })
      .then((res) => {
        res.data.text().then(data => {
          const resJson = JSON.parse(data)
          console.log(resJson)
        })
      })

    handleImportDialogSubmit(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let file = this.importDialogForm.file
          if (Array.isArray(file) && file.length > 0) {
            const data = new FormData()
            let file = this.importDialogForm.file[0]
            data.append('file', this.importDialogForm.file[0].raw)
            ExchangeService.userCardImport(data)
              .then((res) => {
                console.log(res)
                if (
                  res.type ===
                  'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                ) {
                  this.$message.error('自动下载失败的数据')
                  const blob = new Blob([res])
                  const file = new FileReader()

                  file.readAsBinaryString(blob)
                  file.onload = (ev) => {
                    const time = moment(Date.now()).format('YYYYMMDDHHmmss')
                    const myFileName = `兑换卡(券)绑定-失败数据-${time}.xlsx`

                    var urlObject = window.URL || window.webkitURL || window
                    var save_link = document.createElementNS(
                      'http://www.w3.org/1999/xhtml',
                      'a'
                    )
                    save_link.href = urlObject.createObjectURL(blob)
                    save_link.download = myFileName
                    fake_click(save_link)
                    console.log('下载报告')
                  }
                } else if (res.type === 'text/html') {
                  res.text().then((data) => {
                    const resJson = JSON.parse(data)
                    console.log(resJson)
                    if (resJson.code === 200) {
                      this.importDialogVisible = false
                      this.$message.success('操作成功')
                      this.loadList()
                    } else {
                      this.$message.error(resJson.msg)
                    }
                  })
                }
              })
              .catch((error) => {
                console.log(error)
              })
          } else {
            this.$message.error('请选择文件')
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到