前后端分离异步下载的两种方式(axios,xhr)

url: /download/file.php
data: {'path': '/aaa/bbb/ccc.jpg'}

methods: {
        // axios方式下载
        loadLoadFile (url, data) {
            const path = data.path
            const fileName = path.split('/')[path.split('/').length - 1]
            axios.post(url, data, {
            headers: {
                // contentType: 'application/json;charset=UTF-8',
                responseType: 'blob'
            }
            }).then(res => {
                const blob = new Blob([res])
                const url = window.URL.createObjectURL(blob)
                // 创建一个a标签元素,设置下载属性,点击下载,最后移除该元素
                const link = document.createElement('a')
                link.href = url
                link.style.display = 'none'
                // res.headers.fileName 取出后台返回下载的文件名
                // const downlaodFileName = decodeURIComponent(res.headers.filename)
                // const fileName = data.path.split('/')[data.path.split('/').length() - 1]
                link.setAttribute('download', fileName)
                link.click()
                window.URL.revokeObjectURL(url)
                this.$router.back(-1)
            }).catch(error => {
                console.log(error)
            })
        },
        // xhr方式下载
        XHRLoadLoadFile (url, data) {
            const _this = this
            const xhr = new XMLHttpRequest()
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    const blob = new Blob([xhr.response])
                    const url = window.URL.createObjectURL(blob)
                    // 创建一个a标签元素,设置下载属性,点击下载,最后移除该元素
                    const link = document.createElement('a')
                    link.href = url
                    link.style.display = 'none'
                    // 取出下载文件名
                    const disposition = xhr.getResponseHeader('content-disposition')
                    if (disposition === null) {
                        _this.$notification.error({
                            message: '错误',
                            description: '文件未找到',
                            duration: 4
                        })
                    } else {
                        console.log(disposition)
                        const r = /(?<=").*?(?=")/
                        const fileName = disposition.match(r)[0]
                        const downlaodFileName = decodeURIComponent(fileName)
                        link.setAttribute('download', downlaodFileName)
                        link.click()
                        window.URL.revokeObjectURL(url)
                        window.location.href = 'about:blank'
                        window.close()
                    }
                }
            }
            // 将open()以及send()放到 xhr.onreadystatechange 之后生效
            xhr.open('post', '/api/' + url)
            xhr.setRequestHeader('Content-type', 'application/json;charset=UTF-8')
            xhr.setRequestHeader('authorization', Vue.ls.get(ACCESS_TOKEN))
            xhr.responseType = 'arraybuffer/blob'
            xhr.send(JSON.stringify(data))
        }
    }

thinkphp5.1 后台代码

// 下载文件
    public function downFile(Request $request) {
        // 暂时发现不写也能获取
        // header("Access-Control-Expose-Headers: Content-Disposition");
        if( !$request->isPost() ) {
            return error_json("访问方式错误");
        }
        $path = input('path');
        if( empty($path) ) {
            return error_json("要下载的文件不存在");
        }
        $real_path = $this->uploadPath . $path;
        if( file_exists($real_path) ) {
            ob_clean();
            $download =  new \think\response\Download($real_path);
            $name = pathinfo($real_path, PATHINFO_BASENAME);
            return $download->name($name);
            // $filename=iconv('utf-8', 'gb2312', $name);
            // $this->customDown($real_path, $filename);

        } else {
            return error_json("要下载的文件不存在");
        }
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值