前端接收并下载文件流

可以通过将其转化为blob对象,添加到a标签或iframe标签中来模拟下载;如果是在项目中使用,我们需要对请求返回的数据进行处理,这里我们需要把responseType对象格式设置成blob。这里直接用axios请求

function downloadFile(id){

      axios.get(`/api/getFile?id=`+id,

      {

        responseType:'blob'

      }

      ).then((res) => {

        const aEle = document.createElement('a')

        try {

          const blob = res.data

          const filename = 'xxx'

          aEle.style.display = 'none'

          const url = URL.createObjectURL(blob)

          aEle.href = url

          aEle.download = filename

          aEle.click()

          window.URL.revokeObjectURL(url)

        } catch (error) {

          console.log(error);

        }

      }).catch((e) => {

        console.log("请求出错");

      })

    }

猜你喜欢

转载自blog.csdn.net/m0_52276756/article/details/130430821