[英]upon submit download file instead of opening in the browser
目前它在同一個選項卡中打開,想要下載而不是打開。
<form onsubmit="this.action = document.getElementById('selectedfile').value">
<select id="selectedfile">
<option value="/downloads/file1.pdf">File 1</option>
<option value="/downloads/file2.pdf">File 2</option>
<option value="/downloads/file3.pdf">File 3</option>
</select>
<input type="submit" value="Download" class="grey-btn" class="color:#ffffff, backgroud-color:#ff0000;" />
</form>
我不確定這只能用 javascript 來完成。 您需要以不同的方式從您的服務器提供文件。
你使用的是PHP還是什么?
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition
您可以發送一個內容處置標頭來強制下載而不是打開。
更新:
好的,所以我找到了一種在不弄亂服務器的情況下執行此操作的hacky方法。 a
標簽有一個可選的download
屬性,您可以創建並觸發點擊。 然后你可以刪除鏈接。 這是示例代碼:
const form = document.getElementById('form');
form.addEventListener('submit', function(e) {
e.preventDefault();
const selectedValue = document.getElementById('selectedfile').value;
console.log(selectedValue)
const link = document.createElement('a');
link.setAttribute('download', selectedValue);
link.href = selectedValue;
document.body.appendChild(link);
link.click();
});
您當然會從您擁有的當前表單中刪除 onsubmit 並添加一個 id(示例是 #form)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.