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("要下载的文件不存在");
}
}