如何解决如何使用Vue + Laravel强制下载文件
我正在尝试通过laravel检索vue来强制下载文件(不一定是PDF!)。
我到处环顾四周,当我知道它永远都是PDF时,我似乎只能找到方法。但是,如果可能有几种不同的文件类型呢?
解决方法
使用laravel,您可以编写函数下载。也许
$file_url = 'http://www.myremoteserver.com/file.exe';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
readfile($file_url);
示例文件下载为docx文件,然后内容类型为docx的mime => application/vnd.openxmlformats-officedocument.wordprocessingml.document
借助vue,您可以使用axios下载文件。
,我使用此代码下载所有文件。(您必须根据需要对其进行自定义):
对于vuejs组件:
axios.get( 'user/getTicketFile',{
params: {
number: this.$route.params.id,name: item
},responseType: 'blob'
})
.then(function (r)
{
const url = window.URL.createObjectURL(new Blob([r.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download','file.'+r.headers.ext); //or any other extension
document.body.appendChild(link);
link.click();
//hide loader
i.loader = false
});
},
这是laravel后端函数示例:
public function getTicketFile(Request $request)
{
$number = $request['number'];
$name = $request['name'];
$filePath = storage_path( 'app/tickets/'.$number.'/'.$name );
if( file_exists($filePath) )
{
$headers = array(
'ext' => pathinfo($name,PATHINFO_EXTENSION),);
return response()->download($filePath,'',$headers);
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。