代码之家  ›  专栏  ›  技术社区  ›  Matt

无法通过javascript更改下载名称

  •  0
  • Matt  · 技术社区  · 6 年前

    使用下面的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;
    }
    

    尽管进行了更改,但它不会重命名这些文件。我做错了什么?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Scott Marcus    6 年前

    这里有很多不必要的代码。

    你已经宣布 downloadFile 作为一种功能。你不能只是加上 isChrome isSafari 属性,并使用您使用的语法。你必须在十分钟内申报 downLoadFile 作为财产(带有 this.isSafari = ... this.isChrome = ... ).但是,实际上你不需要属性,只需要变量。

    而且,你实际上并没有打电话 下载文件 来自任何地方。

    接下来,在窗口对象上创建新属性并依赖 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");