Не могу изменить имя загрузки через JavaScript - PullRequest
0 голосов
/ 19 мая 2018

Используя приведенный ниже 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;

Насколько я понимаю, код создает ссылку привязки и щелкает по ней, чтобы загрузить файл.Проведя некоторые исследования, я обнаружил, что атрибут download может изменить имя файла , но когда я пытаюсь сделать это с помощью кода, он не работает.Сразу после 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 Ответ

0 голосов
/ 19 мая 2018

У вас здесь много ненужного кода.

Вы объявили 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");
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...