最簡單的:
1.html實現:
<td><a download='<?php echo $name; ?>' href='<?php echo $url; ?>'>下載</a></td>
注意:這個有限制,只能是同源的文件纔可以設置文件名,跨域的雖然可以下載,但是沒辦法設置文件名字,跨域的時候download屬性不起作用。
2.js下載改變文件名:
設置no-cors跨過跨域驗證。
const downloadRes = async (url, name) => {
let response = await fetch(url, {
mode: "no-cors" # fetch設了mode='no-cors'表示不垮域,可以請求成功,但不好意思,你拿不到服務器返回數據,它被標記了'opaque',請求沒發出去請看控制檯網絡面板
})
// 內容轉變成blob地址
let blob = await response.blob()
// 創建隱藏的可下載鏈接
let objectUrl = window.URL.createObjectURL(blob)
let a = document.createElement('a')
//地址
a.href = objectUrl
//修改文件名
a.download = name
// 觸發點擊
document.body.appendChild(a)
a.click()
//移除
setTimeout(() => document.body.removeChild(a), 1000)
}
3.後端實現
前臺顯示:
<td><a href='<?php echo FULL_BASE_URL.'/Commons/download?'.http_build_query(['url'=>$url,'name'=>$name]); ?>'>下載</a></td>
後端方法:
/**
* 文件下載,可跨域,可重命名
* @return [type] [description]
*/
public function download() {
$params=$this->request->query;
$file_url = $params['url'];
$name = $params['name'];
if ($file_url && $name) {
$size=readfile($file_url);
header("Content-type:application/octet-stream");
header("Content-Disposition:attachment;filename=$name");
exit;
}
throw new Exception("參數不對!", 1);
}