js下载文件的几种方式

    技术2022-07-11  132

    1.a标签

      <a href='url' download="文件名"></a>

    2.window.open()

      window.open(‘url’)

    3.通过文件流的方式下载

    axios.get(url, {

        responseType: 'blob',

        headers: {

            // 配置请求头

        }

    }).then((res) => {

        const blob = res.data;

        const reader = new FileReader();

        reader.readAsDataURL(blob);

        reader.onload = (e) => {

            const a = document.createElement('a');

            // 获得文件名解决乱码

            let temp = res.headers["content-disposition"].split(";")[1].split("filename=")[1];

            let iconv = require('iconv-lite');

            iconv.skipDecodeWarning = true;

            let fileName = iconv.decode(temp, 'utf-8');

            a.download = fileName;

            a.href = e.target.result;

            document.body.appendChild(a);

            a.click();

            document.body.removeChild(a);

        }

    })

     

    Processed: 0.014, SQL: 10