簡體   English   中英

從按鈕值的鏈接下載文件

[英]Download a file from a link on button value

我搜索了很多但找不到解決方案我感謝任何可以幫助我的人。

我想在單擊按鈕時下載文件,但基於按鈕文本中的值。

我的 HTML 中有三個這樣的按鈕

<input type="button" onclick="myFunction(this, name1.mp3)" value="button1.mp3">
<input type="button" onclick="myFunction(this, name2.mp3)" value="button2.mp3">
<input type="button" onclick="myFunction(this, name3.mp3)" value="button3.mp3">

我的 JavaScript 是

function myFunction(elmnt, name) {
  var url = "http://mysite*com/" + elmnt.value;
  var downloadFileWithThisName = name;

  ---my download code---


}

如何使用傳遞給函數的名稱下載我的 url?

我應該為---我的下載代碼---部分寫什么?

先感謝您。

function myFunction(elmnt, name) {
  var url = "http://mysite*com/" + elmnt.value;
  const a = document.createElement('a');
      a.href = url;
      a.download = name; // here you can specify your filename
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
}

您可以做的是動態創建一個 A 元素,添加“下載”屬性,設置 Href 並單擊它,所有這些都在代碼中。 然后將其從 DOM 中刪除。

判斷您的代碼的最佳答案如下所示: https : //stackoverflow.com/a/42696866/1891140

var file_path = 'host/path/file.ext';
var a = document.createElement('A');
a.href = file_path;
a.download = file_path.substr(file_path.lastIndexOf('/') + 1);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);

但是您也可以使用簡單的 JQUERY 來實現:

$("<a href='"+url+"' download class='hidden-a'></a>").appendTo("body");
$(".hidden-a")[0].click();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM