通过swagger下载的文档以及将接口接到前端下载都会乱码;但是有一种情况不会乱码,就是直接使用后台的接口地址,也就是说直接使用a标签就不会出现乱码的问题,可是 直接使用a标签,会显着代码不优雅。所以,有了以下解决办法。

// 导入功能中的下载模板功能

    downMoudle() {

      downloadModule().then(res => {

        const url = window.URL.createObjectURL(

          new Blob([res.data], {

            type: 'application/octet-stream'

          })

        )

        const link = document.createElement('a')

        link.href = url

        link.setAttribute(

          'download',

          res.headers['content-disposition'].split('filename=')[1]

        )

        link.click()

      })

    },

    // 导出

    handleCommand(command) {

        exportList2(this.multipleSelection).then(res => {

           const url = window.URL.createObjectURL(

              new Blob(['\ufeff' + res.data], {

                type: 'application/octet-stream'

              })

            )

            const link = document.createElement('a')

            link.href = url

            link.setAttribute(

              'download',

              res.headers['content-disposition'].split('filename=')[1]

            )

            link.click()

          }

        }

 

以下的这段代码也可以实现下载功能,但是我使用下面的代码,会导致下载下来的文件乱码,

有需求的伙伴也可以使用下面的代码试一下

 downMoudle() {

      downloadModule().then(res => {

        const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })

        const url = window.URL || window.webkitURL || window.moxURL

        const downloadHref = url.createObjectURL(blob)

        const downloadLink = document.createElement('a')

        console.log(downloadLink)

        downloadLink.href = downloadHref

        downloadLink.download = '模板.xls'

        downloadLink.click()

        console.log(downloadHref)

      })

    },

 

posted on 2020-08-21 14:25  小名香菜~  阅读(2118)  评论(0编辑  收藏  举报