我在这里指定了一个非常类似的需求。
我需要有用户的浏览器手动启动下载时$('a#someID').click();
但是我不能用窗户。Href方法,因为它将当前页面内容替换为您试图下载的文件。
相反,我想在新窗口/标签中打开下载。这怎么可能呢?
我在这里指定了一个非常类似的需求。
我需要有用户的浏览器手动启动下载时$('a#someID').click();
但是我不能用窗户。Href方法,因为它将当前页面内容替换为您试图下载的文件。
相反,我想在新窗口/标签中打开下载。这怎么可能呢?
当前回答
你必须从服务器和客户端(web应用程序)两方面进行操作。
在服务器上,设置名为Content-Disposition https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition的报头
// nodejs express
res.set('Content-Disposition', `attachment; filename="${self.creationName}"`)
使用上面的头文件,服务器会告诉浏览器响应是一个文件,它应该下载并以给定的名称保存,否则浏览器可能会将文件保存为“attachments (1).zip”之类的文件
接下来,我们查看客户端,创建一个锚链接并自动单击它。
function downloadThroughAnchorLink(downloadUrl: string, fileName: string) {
const a = document.createElement('a')
a.href = downloadUrl;
// We provided a header called Content-Disposition so we dont need to set "a.download" here
// a.download = fileName || 'download'
a.click()
}
这样就行了。
其他回答
这些函数在stacktrace.js中使用:
/**
* Try XHR methods in order and store XHR factory.
*
* @return <Function> XHR function or equivalent
*/
var createXMLHTTPObject = function() {
var xmlhttp, XMLHttpFactories = [
function() {
return new XMLHttpRequest();
}, function() {
return new ActiveXObject('Msxml2.XMLHTTP');
}, function() {
return new ActiveXObject('Msxml3.XMLHTTP');
}, function() {
return new ActiveXObject('Microsoft.XMLHTTP');
}
];
for (var i = 0; i < XMLHttpFactories.length; i++) {
try {
xmlhttp = XMLHttpFactories[i]();
// Use memoization to cache the factory
createXMLHTTPObject = XMLHttpFactories[i];
return xmlhttp;
} catch (e) {
}
}
}
/**
* @return the text from a given URL
*/
function ajax(url) {
var req = createXMLHTTPObject();
if (req) {
try {
req.open('GET', url, false);
req.send(null);
return req.responseText;
} catch (e) {
}
}
return '';
}
如果您不需要浏览另一个页面,这可能会很有帮助。 这是一个基本的javascript函数,所以可以用在任何平台的后端是javascript
window.location.assign('any url or file path')
在尝试下载文件时,会发生很多小事情。浏览器之间的不一致性本身就是一场噩梦。我最终使用了这个很棒的小图书馆。 https://github.com/rndme/download
它的优点是它的灵活性,不仅url,而且客户端数据你想要下载。
文本字符串 文本dataURL 文本的团 文本数组 html字符串 html的团 ajax回调 二进制文件
也可以使用fs-浏览器包。 它有很好的和简单的下载方法为客户端。 它是这样的:
import {downloadFile} from 'fs-browsers'; downloadFile (url-to-the-file);
function downloadURI(uri, name)
{
var link = document.createElement("a");
// If you don't know the name or want to use
// the webserver default set name = ''
link.setAttribute('download', name);
link.href = uri;
document.body.appendChild(link);
link.click();
link.remove();
}
检查您的目标浏览器是否能够顺利运行上面的代码片段:http://caniuse.com/#feat=download