vue + thinkphp5 下载各类型文件
看了很多资料,感觉都不是很完整,就自己写了一个给大家看看。
我是吧文件转成base64去进行下载的,个人觉得比较方便,后台加参数也比较方便。
vue代码
先拿到需要下载文件
funDown: function(index, row){
var that = this
that
.$confirm('此操作将下载用户上传的招聘简介, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
})
.then(() => {
const param = {
id: row.id
}
exhibitorsDownGeneral(param)
.then(res => {
let aLink = document.createElement('a');
let blob = this.base64ToBlob(res.data.files); //new Blob([content]);
let evt = document.createEvent("HTMLEvents");
console.log("点击下载",evt)
evt.initEvent("click", true, true);//initEvent 不加后两个参数在FF下会报错 事件类型,是否冒泡,是否阻止浏览器的默认行为
aLink.download = res.data.companyname;
aLink.href = URL.createObjectURL(blob);
aLink.click()
})
})
.catch(() => {})
},
base转成blob流
base64ToBlob(code) {
let parts = code.split(';base64,');
let contentType = parts[0].split(':')[1];
let raw = window.atob(parts[1]);
let rawLength = raw.length;
let uInt8Array = new Uint8Array(rawLength);
for (let i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], {type: contentType});
},
thinkphp5代码
拿到文件然后转成base64,但是我发现他不带前缀,就自己做了一个前缀转换
/**
* 下载
* @return string
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
* @Date: 10:34 2021/11/4
*/
public function downGeneral(){
$id = input('post.id/a');
$reg = model('JobfairExhibitors')->where('id',$id[0])->find();
$file_lj = str_replace("\\","/",ROOT_PATH.'public/upload/');
$files = $file_lj.$reg['general'];
if(!file_exists($files)){
$this->ajaxReturn(500, '文件不存在');
}else {
$suffix = explode('.',$files);
$reg['files'] = $this->houzui(end($suffix)) . base64_encode (file_get_contents($files));
$this->ajaxReturn(200,'文件下载中~',$reg);
}
}
/**
* bser64前缀转换
* @param $str
* @return string
* @Date: user
*/
public function houzui($str){
$suffix_str = '';
switch ($str){
case 'xlsx':
$suffix_str = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
break;
case 'png':
$suffix_str = 'image/png';
break;
case 'jpg':
$suffix_str = 'image/jpeg';
break;
case 'doc':
$suffix_str = 'application/msword';
break;
case 'docx':
$suffix_str = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
break;
}
return 'data:'.$suffix_str.';base64,';
}