mko*_*yak 104 javascript
什么是最好的跨浏览器方式来打开下载对话框(假设我们可以设置内容处置:标题中的附件)而无需导航离开当前页面,或打开弹出窗口,这在IE6中无法正常工作.
moz*_*ras 188
这个javascript很好,它不会打开一个新窗口或选项卡.
window.location.assign(url);
Run Code Online (Sandbox Code Playgroud)
0x0*_*00f 90
7年过去了,好的.我不知道它是否适用于IE6,但这会在FF和Chrome中提示OpenFileDialog.
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);
Run Code Online (Sandbox Code Playgroud)
jao*_*jao 23
我总是在下载链接中添加一个target ="_ blank".这将打开一个新窗口,但只要用户单击"保存",新窗口就会关闭.
Geo*_*orn 19
将其放在HTML头部分中,将urlvar 设置为要下载的文件的URL:
<script type="text/javascript">
function startDownload()
{
var url='http://server/folder/file.ext';
window.open(url, 'Download');
}
</script>
Run Code Online (Sandbox Code Playgroud)
然后把它放在体内,这将在5秒后自动开始下载:
<script type="text/javascript">
setTimeout('startDownload()', 5000); //starts download after 5 seconds
</script>
Run Code Online (Sandbox Code Playgroud)
(从这里开始.)
alo*_*d05 15
正如这个问题所暗示的那样,我一直在寻找一种使用javascript来启动文件下载的好方法.然而,这些答案没有帮助.然后我做了一些xbrowser测试,发现iframe在IE> 8的所有现代浏览器上效果最好.
downloadUrl = "http://example.com/download/file.zip";
var downloadFrame = document.createElement("iframe");
downloadFrame.setAttribute('src',downloadUrl);
downloadFrame.setAttribute('class',"screenReaderText");
document.body.appendChild(downloadFrame);
Run Code Online (Sandbox Code Playgroud)
class="screenReaderText" 是我的类来设置存在但不可见的内容.
CSS:
.screenReaderText {
border: 0;
clip: rect(0 0 0 0);
height: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
width: 1px;
}
Run Code Online (Sandbox Code Playgroud)
与html5boilerplate中的.visuallyHidden相同
我更喜欢这个javascript window.open方法,因为如果链接被破坏,iframe方法根本不做任何事情,而不是重定向到空白页面说文件无法打开.
window.open(downloadUrl, 'download_window', 'toolbar=0,location=no,directories=0,status=0,scrollbars=0,resizeable=0,width=1,height=1,top=0,left=0');
window.focus();
Run Code Online (Sandbox Code Playgroud)
我知道问题已被问到,7 years and 9 months ago但许多发布的解决方案似乎不起作用,例如<iframe>仅使用作品FireFox但不能使用Chrome.
最佳方案:
打开文件下载弹出窗口的最佳工作解决方案JavaScript是使用HTML链接元素,而无需将链接元素附加到document.body其他答案中所述的链接元素.
您可以使用以下功能:
function downloadFile(filePath){
var link=document.createElement('a');
link.href = filePath;
link.download = filePath.substr(filePath.lastIndexOf('/') + 1);
link.click();
}
Run Code Online (Sandbox Code Playgroud)
在我的应用程序中,我这样使用它:
downloadFile('report/xls/myCustomReport.xlsx');
Run Code Online (Sandbox Code Playgroud)
工作演示:
function downloadFile(filePath) {
var link = document.createElement('a');
link.href = filePath;
link.download = filePath.substr(filePath.lastIndexOf('/') + 1);
link.click();
}
downloadFile("http://www.adobe.com/content/dam/Adobe/en/accessibility/pdfs/accessing-pdf-sr.pdf");Run Code Online (Sandbox Code Playgroud)
注意:
link.download属性,以便浏览器不会在新选项卡中打开该文件并触发下载弹出窗口.使用 HTML5 Blob对象-URL 文件 API:
/**
* Save a text as file using HTML <a> temporary element and Blob
* @see /sf/ask/3499174171/
* @param fileName String
* @param fileContents String JSON String
* @author Loreto Parisi
*/
var saveBlobAsFile = function(fileName,fileContents) {
if(typeof(Blob)!='undefined') { // using Blob
var textFileAsBlob = new Blob([fileContents], { type: 'text/plain' });
var downloadLink = document.createElement("a");
downloadLink.download = fileName;
if (window.webkitURL != null) {
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
}
else {
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.onclick = document.body.removeChild(event.target);
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
} else {
var pp = document.createElement('a');
pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents));
pp.setAttribute('download', fileName);
pp.onclick = document.body.removeChild(event.target);
pp.click();
}
}//saveBlobAsFile
Run Code Online (Sandbox Code Playgroud)
/**
* Save a text as file using HTML <a> temporary element and Blob
* @see https://stackoverflow.com/questions/49988202/macos-webview-download-a-html5-blob-file
* @param fileName String
* @param fileContents String JSON String
* @author Loreto Parisi
*/
var saveBlobAsFile = function(fileName,fileContents) {
if(typeof(Blob)!='undefined') { // using Blob
var textFileAsBlob = new Blob([fileContents], { type: 'text/plain' });
var downloadLink = document.createElement("a");
downloadLink.download = fileName;
if (window.webkitURL != null) {
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
}
else {
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.onclick = document.body.removeChild(event.target);
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
} else {
var pp = document.createElement('a');
pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents));
pp.setAttribute('download', fileName);
pp.onclick = document.body.removeChild(event.target);
pp.click();
}
}//saveBlobAsFile
Run Code Online (Sandbox Code Playgroud)
如果链接是有效的文件URL,只需指定window.location.href即可.
但是,有时链接无效,并且需要iFrame.
执行正常的event.preventDefault以防止窗口打开,如果您使用的是jQuery,这将起作用:
$('<iframe>').attr('src', downloadThing.attr('href')).appendTo('body').on("load", function() {
$(this).remove();
});
Run Code Online (Sandbox Code Playgroud)
修改窗口的位置可能会引起一些问题,尤其是当您拥有像websocket这样的持久连接时。因此,我总是采用良好的旧iframe解决方案。
的HTML
<input type="button" onclick="downloadButtonClicked()" value="Download"/>
...
...
...
<iframe style="display:none;" name="hiddenIframe" id="hiddenIframe"></iframe>
Run Code Online (Sandbox Code Playgroud)
Java脚本
function downloadButtonClicked() {
// Simulate a link click
var url = 'your_download_url_here';
var elem = document.createElement('a');
elem.href = url;
elem.target = 'hiddenIframe';
elem.click();
}
Run Code Online (Sandbox Code Playgroud)
根据新的 chrome 规范的最佳解决方案https://developers.google.com/web/updates/2018/02/chrome-65-deprecations
普通 JavaScript
public static downloadFile(url: string): void {
const xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = () => {
if (xmlHttp.readyState === 4 && xmlHttp.status === 200) {
const blobUrl = window.URL.createObjectURL(xmlHttp.response);
const e = document.createElement('a');
e.href = blobUrl;
e.download = blobUrl.substr(blobUrl.lastIndexOf('/') + 1);
document.body.appendChild(e);
e.click();
document.body.removeChild(e);
}
};
xmlHttp.responseType = 'blob';
xmlHttp.open('GET', url, true);
xmlHttp.send(null);
}
Run Code Online (Sandbox Code Playgroud)
如果您使用的是角度尝试这个。
async downloadBrochure(url: string) {
try {
const res = await this.httpClient.get(url, { responseType: 'blob' }).toPromise();
this.downloadFile(res);
} catch (e) {
console.log(e.body.message);
}
}
downloadFile(data) {
const url = window.URL.createObjectURL(data);
const e = document.createElement('a');
e.href = url;
e.download = url.substr(url.lastIndexOf('/') + 1);
document.body.appendChild(e);
e.click();
document.body.removeChild(e);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
264349 次 |
| 最近记录: |