先說下需求:正常點擊免責聲明是下載的文件,根據用戶需求是點擊預覽,所以這里利用phpword生成一個靜態頁面並進行預覽。不多說,直接上代碼附帶類文件。
類文件:https://pan.baidu.com/s/1yhZu5JyrtIfKnGllRblPtg 提取碼:fbu3 把類文件放在vendor目錄下。
html代碼:
<!-- 這里是點擊下載的html代碼,隱藏域是當前的id -->
<p><input type="hidden" value="{$vo.file_id}" class="file_id"><a href="#" class="btn btn-primary click">點擊下載</a></p>
<script type="">
//觸發ajax把id傳到控制器
$('.click').click(function(){
id = $(this).prev().val();
$.ajax({
type: "POST",
url: "{:url('home/Single/ajax')}",
data: {id:id},
dataType: "json",
success: function (msg) {
window.open(msg.html)//新頁面打開預覽
}
});
return false;
})
</script>
后台代碼:
//首先頭部引用類
use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\PhpWord;
public function ajax(){
//根據id查詢數據庫存的文檔路徑
$file_id = $_POST['id'];
$info = M('download_file')->where(['file_id'=>$file_id])->find();
$IOFactory = new PhpWord();
$phpWord = \PhpOffice\PhpWord\IOFactory::load('./'.$info['file_url']);
$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, "HTML");
//生成hello.html文件路徑
$xmlWriter->save('./Public/doc/hello.html');
//判斷文件是否存在,額庵后傳到前台
if(file_exists('./Public/doc/hello.html')){
$html='/Public/doc/hello.html';
$dataa = array('html'=>$html,'url'=>$url);
echo json_encode($dataa);
}else{
$dataa = array('html'=>'0');
echo json_encode($dataa);
}
}
