今天有個使用a標簽下載一個 .txt 文件,但是使用了不少方法,在點擊下載的時候總是會直接打開被下載的文件,但是下載其他格式的文件就不會;也在網上找了不少資料
一、嘗試href + download方法
有得說
測試是頁面是這樣
二、嘗試另一種href + download方法
也有人說
要不就是這樣
三、嘗試createElement方法
也使用過這種
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
download("hello.txt","This is the content of my file :)")
這個直接創建的文件可以下載,但是
將element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
改為服務端地址如element.setAttribute('href', 'fileurl');
就不行了
四、嘗試form 方法
也使用過這種
$('<form method="post" target="_blank" role="form" action="'+data.urlPath+data.fileName+'" hidden="hidden"></form>') .appendTo('body').submit().remove();
這個一用頁面這樣了
暈!
五、嘗試XMLHttpRequest方法
還用過這種
function downloadIamge() {
var url = "";
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);//get請求,請求地址,是否異步
xhr.responseType = "blob"; // 返回類型blob
xhr.onload = function () {// 請求完成處理函數
if (this.status === 200) {
var blob = this.response;// 獲取返回值
var a = document.createElement('a');
a.download = 'data.doc';
a.href=window.URL.createObjectURL(blob);
a.click();
}
};
// 發送ajax請求
xhr.send();
}
但是這個好像把事情搞大了,下個文件而已嘛,還得把XMLHttpRequest
請來感覺有些大材小用了(並且這里沒有使用到 后端接口,沒有設置允許跨域可想而知請求是不可能成功的),還是重新再找
六、最終還是使用href + download方法解決問題
最后仔細一想,等等,好像get到了,其實就是這個a他在認識的文件的情況下出現了跳轉嗎!所以有時候下載其他什么壓縮包之類的其他類型文件都能順利搞定
那問題就簡單了
看
<!--標簽屬性href,使其指向空或不返回任何內容。如:-->
<a href="javascript:void(0);" >點此無反應javascript:void(0)</a>
<a href="javascript:;" >點此無反應javascript:</a>
<!--標簽事件onclick,阻止其默認行為。如:-->
<a href="" onclick="return false;">return false;</a>
<a href="#" onclick="return false;">return false;</a>
最后將頁面修改為
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>test file download by tag of a</title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
<a href="#" download="fileurl">download8888</a>
</body>
</html>
哎,這么簡單糾結半天,再次留下了沒有技術的眼淚