Как определить, когда при вводе файла нажимается отмена?

Более короткая форма:

[ -d "$DIR" ] && echo "Yes"
97
задан Ppp 7 January 2011 в 17:46
поделиться

1 ответ

Существует несколько предлагаемых решений в этом потоке и этой трудности к обнаружению, когда пользовательские щелчки, кнопка "Cancel" на рамке выделения файла является проблемой, которая влияет на многих людей.

факт - то, что существует номер 100%-й надежный способ обнаружить, если пользователь нажал кнопку "Cancel" на рамку выделения файла. Но существуют пути к [1 113], надежно обнаруживают, если пользователь добавил файл к входному файлу. Таким образом, это - основная стратегия этого ответа!

я решил добавить этот ответ, потому что, по-видимому, другие ответы не работают над большинством браузеров или гарантируемый на мобильных устройствах.

Кратко код основан на 3 точках:

  1. входной файл первоначально создается динамично в "памяти" в js (мы не добавляем его к "HTML" в данный момент);
  2. После добавления файла затем входной файл добавляется к HTML, иначе ничто не происходит;
  3. удаление файла сделано путем удаления входного файла из HTML определенным событием, что означает, что "редактирование" / "модификация" файла сделано путем удаления старого входного файла и создания нового.

Для лучшего понимания смотрят на код ниже и примечания также.

[...]
<button type="button" onclick="addIptFl();">ADD INPUT FILE!</button>
<span id="ipt_fl_parent"></span>
[...]
function dynIptFl(jqElInst, funcsObj) {
    if (typeof funcsObj === "undefined" || funcsObj === "") {
        funcsObj = {};
    }
    if (funcsObj.hasOwnProperty("before")) {
        if (!funcsObj["before"].hasOwnProperty("args")) {
            funcsObj["before"]["args"] = [];
        }
        funcsObj["before"]["func"].apply(this, funcsObj["before"]["args"]);
    }
    var jqElInstFl = jqElInst.find("input[type=file]");

    // NOTE: Open the file selection box via js. By Questor
    jqElInstFl.trigger("click");

    // NOTE: This event is triggered if the user selects a file. By Questor
    jqElInstFl.on("change", {funcsObj: funcsObj}, function(e) {

        // NOTE: With the strategy below we avoid problems with other unwanted events
        // that may be associated with the DOM element. By Questor
        e.preventDefault();

        var funcsObj = e.data.funcsObj;
        if (funcsObj.hasOwnProperty("after")) {
            if (!funcsObj["after"].hasOwnProperty("args")) {
                funcsObj["after"]["args"] = [];
            }
            funcsObj["after"]["func"].apply(this, funcsObj["after"]["args"]);
        }
    });

}

function remIptFl() {

    // NOTE: Remove the input file. By Questor
    $("#ipt_fl_parent").empty();

}

function addIptFl() {

    function addBefore(someArgs0, someArgs1) {
    // NOTE: All the logic here happens just before the file selection box opens.
    // By Questor

        // SOME CODE HERE!

    }

    function addAfter(someArgs0, someArgs1) {
    // NOTE: All the logic here happens only if the user adds a file. By Questor

        // SOME CODE HERE!

        $("#ipt_fl_parent").prepend(jqElInst);

    }

    // NOTE: The input file is hidden as all manipulation must be done via js.
    // By Questor
    var jqElInst = $('\
<span>\
    <button type="button" onclick="remIptFl();">REMOVE INPUT FILE!</button>\
    <input type="file" name="input_fl_nm" style="display: block;">\
</span>\
');

    var funcsObj = {
        before: {
            func: addBefore,
            args: [someArgs0, someArgs1]
        },
        after: {
            func: addAfter,

            // NOTE: The instance with the input file ("jqElInst") could be passed
            // here instead of using the context of the "addIptFl()" function. That
            // way "addBefore()" and "addAfter()" will not need to be inside "addIptFl()",
            // for example. By Questor
            args: [someArgs0, someArgs1]

        }
    };
    dynIptFl(jqElInst, funcsObj);

}

Спасибо! =D

0
ответ дан 24 November 2019 в 05:30
поделиться
Другие вопросы по тегам:

Похожие вопросы: