使用下面的javascript,我可以在浏览器上没有任何问题下载文件,但我遇到的一个问题是我需要在下载后重命名文件。
这是下载文件的功能:
window.downloadFile = function (sUrl) {
//iOS devices do not support downloading. We have to inform user about this.
if (/(iP)/g.test(navigator.userAgent)) {
alert('Your device do not support files downloading. Please try again in desktop browser.');
return false;
}
//If in Chrome or Safari - download via virtual link click
if (window.downloadFile.isChrome || window.downloadFile.isSafari) {
//Creating new link node.
var link = document.createElement('a');
link.href = sUrl;
if (link.download !== undefined) {
//Set HTML5 download attribute. This will prevent file from opening if supported.
var fileName = sUrl.substring(sUrl.lastIndexOf('/') + 1, sUrl.length);
link.download = fileName;
}
//Dispatching click event.
if (document.createEvent) {
var e = document.createEvent('MouseEvents');
e.initEvent('click', true, true);
link.dispatchEvent(e);
return true;
}
}
// Force file download (whether supported by server).
var query = '?download';
window.open(sUrl + query, '_self');
}
window.downloadFile.isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
window.downloadFile.isSafari = navigator.userAgent.toLowerCase().indexOf('safari') > -1;
根据我的理解,代码会创建一个锚链接并点击它来下载文件。在做了一些研究之后I found that the download
attribute can change the file name,但是当我用代码尝试这个时它不起作用。在link.href = sUrl;
之后我添加了link.download = random()+".png";
以及以下功能:
function random() {
var length = 32,
charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
retVal = "";
for (var i = 0, n = charset.length; i < length; ++i) {
retVal += charset.charAt(Math.floor(Math.random() * n));
}
return retVal;
}
尽管进行了更改,但它不会重命名文件。我做错了什么?
答案 0 :(得分:0)
你在这里有很多不必要的代码。
您已将downloadFile
声明为函数。然后,您只能使用您正在使用的语法向其添加isChrome
和isSafari
属性。您必须在downLoadFile
内将其声明为属性(this.isSafari = ...
和this.isChrome = ...
)。但是,你真的不需要属性,只需要变量。
此外,您实际上并未从任何地方拨打downloadFile
。
接下来,在窗口对象上创建新属性并依赖navigator.userAgent
是反模式。这正是我们不想做的事情。
您也不需要检查link.download
。只需设置它。如果浏览器支持它,它将使用它。如果没有,它就不会。如果它不受支持,它不会抛出错误。
而且,您只需使用link.click()
而不是创建和分派事件。
请参阅内联评论了解更多信息:
// If you are going to add properties to window, at least set them up in a
// namespace that you are 100% sure doesn't already exist.
window.CustomNamespace = {};
window.CustomNamespace.downloadFile = function (sUrl) {
// Create new link node.
var link = document.createElement('a');
link.href = sUrl;
// Browser detection is a futile effort because navigator.userAgent will often
// return inaccurate information and can be spoofed easily, creating security
// holes in your application. Additionally, testing for all the different clients
// and platforms is a never ending task. Use feature detection.
// All you really care about is whether the client supports the feature.
// You don't need to know what kind of client it is.
if (link.download) {
// download is supported. Just use it. Do you really care what browser it is?
link.download = random() + ".png";
console.log(link.download);
link.click(); // Trigger the click event - no need to create/dispatch a new event.
} else {
alert('Your device do not support files downloading. Please try again in desktop browser.');
}
}
function random() {
var length = 32,
charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
retVal = "";
for (var i = 0, n = charset.length; i < length; ++i) {
retVal += charset.charAt(Math.floor(Math.random() * n));
}
return retVal;
}
// Invoke the function
window.CustomNamespace.downloadFile("test");
&#13;