在不离开页面的情况下打开下载窗口的最简单方法

时间:2022-10-22 14:39:33

What is the best cross browser way to open a download dialog (lets assume we can set content-disposion:attachment in the headers) without navigating away from the current page, or opening popups, which doesnt work well in IE6.

什么是最好的跨浏览器方式来打开下载对话框(假设我们可以设置内容处置:标题中的附件)而无需导航离开当前页面,或打开弹出窗口,这在IE6中无法正常工作。

11 个解决方案

#1


53  

7 years have passed, ok. I don't know is it work for IE6, but this prompts OpenFileDialog in FF and Chrome.

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);

#2


163  

This javascript is nice that it doesn't open a new window or tab.

这个javascript很好,它不会打开一个新的窗口或选项卡。

window.location.assign(url);

#3


18  

I always add a target="_blank" to the download link. This will open a new window, but as soon as the user clicks save, the new window is closed.

我总是在下载链接中添加一个target =“_ blank”。这将打开一个新窗口,但只要用户单击“保存”,新窗口就会关闭。

#4


13  

I've been looking for a good way to use javascript to initiate the download of a file, just as this question suggests. However these answers not been helpful. I then did some xbrowser testing and have found that an iframe works best on all modern browsers IE>8.

正如这个问题所暗示的那样,我一直在寻找一种使用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); 

class="screenReaderText" is my class to style content that is present but not viewable.

class =“screenReaderText”是我的类,用于设置存在但不可查看的内容。

css:

CSS:

.screenReaderText { 
  border: 0; 
  clip: rect(0 0 0 0); 
  height: 1px; 
  margin: -1px; 
  overflow: hidden; 
  padding: 0; 
  position: absolute; 
  width: 1px; 
}

same as .visuallyHidden in html5boilerplate

与html5boilerplate中的.visuallyHidden相同

I prefer this to the javascript window.open method because if the link is broken the iframe method simply doesn't do anything as opposed to redirecting to a blank page saying the file could not be opened.

我更喜欢这个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();

#5


13  

Put this in the HTML head section, setting the url var to the URL of the file to be downloaded:

把它放在HTML头部分,将url var设置为要下载的文件的URL:

<script type="text/javascript">  
function startDownload()  
{  
     var url='http://server/folder/file.ext';    
     window.open(url, 'Download');  
}  
</script>

Then put this in the body, which will start the download automatically after 5 seconds:

然后把它放在体内,这将在5秒后自动开始下载:

<script type="text/javascript">  
setTimeout('startDownload()', 5000); //starts download after 5 seconds  
</script> 

(From here.)

(从这里。)

#6


6  

I know the question was asked 7 years and 9 months ago but many posted solutions doesn't seem to work, for example using an <iframe> works only with FireFox and doesn't work with Chrome.

我知道问题是在7年零9个月前提出的,但许多发布的解决方案似乎不起作用,例如使用

Best solution:

最佳方案:

The best working solution to open a file download pop-up in JavaScript is to use a HTML link element, with no need to append the link element to the document.body as stated in other answers.

在JavaScript中打开文件下载弹出窗口的最佳工作解决方案是使用HTML链接元素,而不需要将link元素附加到document.body,如其他答案中所述。

You can use the following function:

您可以使用以下功能:

function downloadFile(filePath){
    var link=document.createElement('a');
    link.href = filePath;
    link.download = filePath.substr(filePath.lastIndexOf('/') + 1);
    link.click();
}

In my application, I am using it this way:

在我的应用程序中,我这样使用它:

downloadFile('report/xls/myCustomReport.xlsx');

Working Demo:

工作演示:

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");

Note:

注意:

  • You have to use the link.download attribute so the browser doesn't open the file in a new tab and fires the download pop-up.
  • 您必须使用link.download属性,以便浏览器不会在新选项卡中打开该文件并触发下载弹出窗口。
  • This was tested with several file types (docx, xlsx, png, pdf, ...).
  • 这是使用多种文件类型(docx,xl​​sx,png,pdf,...)测试的。

#7


5  

If the link is to a valid file url, simply assigning window.location.href will work.

如果链接是有效的文件URL,只需指定window.location.href即可。

However, sometimes the link is not valid, and an iFrame is required.

但是,有时链接无效,并且需要iFrame。

Do your normal event.preventDefault to prevent the window from opening, and if you are using jQuery, this will work:

执行正常的event.preventDefault以防止窗口打开,如果您使用的是jQuery,这将起作用:

$('<iframe>').attr('src', downloadThing.attr('href')).appendTo('body').load(function() {
   $(this).remove();
});

#8


0  

How about:

怎么样:

<meta http-equiv="refresh" content="5;url=http://site.com/file.ext">

This way works on all browsers (i think) and let you put a message like: "If the download doesn't start in five seconds, click here."

这种方式适用于所有浏览器(我认为),并让您发出如下消息:“如果下载没有在五秒内开始,请单击此处。”

If you need it to be with javascript.. well...

如果你需要它与javascript ..好吧...

document.write('<meta http-equiv="refresh" content="5;url=http://site.com/file.ext">');

Regards

问候

#9


0  

A small/hidden iframe can work for this purpose.

小/隐藏的iframe可以用于此目的。

That way you don't have to worry about closing the pop up.

这样你就不必担心关闭弹出窗口了。

#10


0  

Modifying the location of window might cause some issue especially when you have a persistent connection like websocket. So I always resort to good old iframe solution.

修改窗口的位置可能会导致一些问题,尤其是当您有像websocket这样的持久连接时。所以我总是求助于旧的iframe解决方案。

HTML

HTML

<input type="button" onclick="downloadButtonClicked()" value="Download"/>
...
...
...
<iframe style="display:none;" name="hiddenIframe" id="hiddenIframe"></iframe>

Javascript

使用Javascript

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();
}

#11


0  

Using HTML5 Blob Object-URL File API:

使用HTML5 Blob Object-URL文件API:

/**
 * Save a text as file using HTML <a> temporary element and Blob
 * @see https://*.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

/**
 * Save a text as file using HTML <a> temporary element and Blob
 * @see https://*.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

var jsonObject = {
  "name": "John",
  "age": 31,
  "city": "New York"
};
var fileContents = JSON.stringify(jsonObject, null, 2);
var fileName = "data.json";

saveBlobAsFile(fileName, fileContents)

#1


53  

7 years have passed, ok. I don't know is it work for IE6, but this prompts OpenFileDialog in FF and Chrome.

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);

#2


163  

This javascript is nice that it doesn't open a new window or tab.

这个javascript很好,它不会打开一个新的窗口或选项卡。

window.location.assign(url);

#3


18  

I always add a target="_blank" to the download link. This will open a new window, but as soon as the user clicks save, the new window is closed.

我总是在下载链接中添加一个target =“_ blank”。这将打开一个新窗口,但只要用户单击“保存”,新窗口就会关闭。

#4


13  

I've been looking for a good way to use javascript to initiate the download of a file, just as this question suggests. However these answers not been helpful. I then did some xbrowser testing and have found that an iframe works best on all modern browsers IE>8.

正如这个问题所暗示的那样,我一直在寻找一种使用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); 

class="screenReaderText" is my class to style content that is present but not viewable.

class =“screenReaderText”是我的类,用于设置存在但不可查看的内容。

css:

CSS:

.screenReaderText { 
  border: 0; 
  clip: rect(0 0 0 0); 
  height: 1px; 
  margin: -1px; 
  overflow: hidden; 
  padding: 0; 
  position: absolute; 
  width: 1px; 
}

same as .visuallyHidden in html5boilerplate

与html5boilerplate中的.visuallyHidden相同

I prefer this to the javascript window.open method because if the link is broken the iframe method simply doesn't do anything as opposed to redirecting to a blank page saying the file could not be opened.

我更喜欢这个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();

#5


13  

Put this in the HTML head section, setting the url var to the URL of the file to be downloaded:

把它放在HTML头部分,将url var设置为要下载的文件的URL:

<script type="text/javascript">  
function startDownload()  
{  
     var url='http://server/folder/file.ext';    
     window.open(url, 'Download');  
}  
</script>

Then put this in the body, which will start the download automatically after 5 seconds:

然后把它放在体内,这将在5秒后自动开始下载:

<script type="text/javascript">  
setTimeout('startDownload()', 5000); //starts download after 5 seconds  
</script> 

(From here.)

(从这里。)

#6


6  

I know the question was asked 7 years and 9 months ago but many posted solutions doesn't seem to work, for example using an <iframe> works only with FireFox and doesn't work with Chrome.

我知道问题是在7年零9个月前提出的,但许多发布的解决方案似乎不起作用,例如使用

Best solution:

最佳方案:

The best working solution to open a file download pop-up in JavaScript is to use a HTML link element, with no need to append the link element to the document.body as stated in other answers.

在JavaScript中打开文件下载弹出窗口的最佳工作解决方案是使用HTML链接元素,而不需要将link元素附加到document.body,如其他答案中所述。

You can use the following function:

您可以使用以下功能:

function downloadFile(filePath){
    var link=document.createElement('a');
    link.href = filePath;
    link.download = filePath.substr(filePath.lastIndexOf('/') + 1);
    link.click();
}

In my application, I am using it this way:

在我的应用程序中,我这样使用它:

downloadFile('report/xls/myCustomReport.xlsx');

Working Demo:

工作演示:

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");

Note:

注意:

  • You have to use the link.download attribute so the browser doesn't open the file in a new tab and fires the download pop-up.
  • 您必须使用link.download属性,以便浏览器不会在新选项卡中打开该文件并触发下载弹出窗口。
  • This was tested with several file types (docx, xlsx, png, pdf, ...).
  • 这是使用多种文件类型(docx,xl​​sx,png,pdf,...)测试的。

#7


5  

If the link is to a valid file url, simply assigning window.location.href will work.

如果链接是有效的文件URL,只需指定window.location.href即可。

However, sometimes the link is not valid, and an iFrame is required.

但是,有时链接无效,并且需要iFrame。

Do your normal event.preventDefault to prevent the window from opening, and if you are using jQuery, this will work:

执行正常的event.preventDefault以防止窗口打开,如果您使用的是jQuery,这将起作用:

$('<iframe>').attr('src', downloadThing.attr('href')).appendTo('body').load(function() {
   $(this).remove();
});

#8


0  

How about:

怎么样:

<meta http-equiv="refresh" content="5;url=http://site.com/file.ext">

This way works on all browsers (i think) and let you put a message like: "If the download doesn't start in five seconds, click here."

这种方式适用于所有浏览器(我认为),并让您发出如下消息:“如果下载没有在五秒内开始,请单击此处。”

If you need it to be with javascript.. well...

如果你需要它与javascript ..好吧...

document.write('<meta http-equiv="refresh" content="5;url=http://site.com/file.ext">');

Regards

问候

#9


0  

A small/hidden iframe can work for this purpose.

小/隐藏的iframe可以用于此目的。

That way you don't have to worry about closing the pop up.

这样你就不必担心关闭弹出窗口了。

#10


0  

Modifying the location of window might cause some issue especially when you have a persistent connection like websocket. So I always resort to good old iframe solution.

修改窗口的位置可能会导致一些问题,尤其是当您有像websocket这样的持久连接时。所以我总是求助于旧的iframe解决方案。

HTML

HTML

<input type="button" onclick="downloadButtonClicked()" value="Download"/>
...
...
...
<iframe style="display:none;" name="hiddenIframe" id="hiddenIframe"></iframe>

Javascript

使用Javascript

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();
}

#11


0  

Using HTML5 Blob Object-URL File API:

使用HTML5 Blob Object-URL文件API:

/**
 * Save a text as file using HTML <a> temporary element and Blob
 * @see https://*.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

/**
 * Save a text as file using HTML <a> temporary element and Blob
 * @see https://*.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

var jsonObject = {
  "name": "John",
  "age": 31,
  "city": "New York"
};
var fileContents = JSON.stringify(jsonObject, null, 2);
var fileName = "data.json";

saveBlobAsFile(fileName, fileContents)