0

我正在尝试使用字符替代对消息加密/解密页面进行编码。我设法将密钥保存到文件中,我想将其加载回来。我设法通过以下方式成功加载密钥:

    <script>
    function loadkey () {
    var keyToLoad = document.getElementById("keyToLoad").files[0];
    var keyReader = new FileReader();
    keyReader.onload = function(keyLoadEvent)
    {
        var keyFromFileLoaded = keyLoadEvent.target.result;
        document.getElementById("key").value = keyFromFileLoaded;
    };
    keyReader.readAsText(keyToLoad, "utf-8");
}
</script>

<h3>Put your key here</h3>
<textarea id="key" cols="30" rows="1"></textarea>
<br>
<button onclick="genKey()">Generate  key</button>
<button onclick="savekey()">Save key</button>
<input type="file" id="keyToLoad">
<button onclick="loadkey()">Load key</button>

但是单独使用选择文件按钮和加载键按钮看起来真的很愚蠢。所以我隐藏输入按钮并通过单击加载键按钮触发它:

<script>
    function handleChooseKey()
{
    document.getElementById("keyToLoad").click();
}

function loadkey () {
    var keyToLoad = document.getElementById("keyToLoad").files[0];
    var keyReader = new FileReader();
    keyReader.onload = function(keyLoadEvent)
    {
        var keyFromFileLoaded = keyLoadEvent.target.result;
        document.getElementById("key").value = keyFromFileLoaded;
    };
    keyReader.readAsText(keyToLoad, "utf-8");
}
</script>

<h3>Put your key here</h3>
<textarea id="key" cols="30" rows="1"></textarea>
<br>
<button onclick="genKey()">Generate  key</button>
<button onclick="savekey()">Save key</button>
<input type="file" id="keyToLoad" style="display:none;">
<button onclick="handleChooseKey();loadkey();">Load key</button>

我的问题是它不能在加载密钥文件后立即使 loadkey() 函数工作,因此在下次单击之前不会加载密钥。请帮我。谢谢 :)

4

1 回答 1

0

试试这个:

<script>
    function handleChooseKey()
{
    document.getElementById("keyToLoad").click();
    document.getElementById("keyToLoad").onchange = function(e) { loadkey() };
}

function loadkey () {
    var keyToLoad = document.getElementById("keyToLoad").files[0];
    var keyReader = new FileReader();
    keyReader.onload = function(keyLoadEvent)
    {
        var keyFromFileLoaded = keyLoadEvent.target.result;
        document.getElementById("key").value = keyFromFileLoaded;
    };
    keyReader.readAsText(keyToLoad, "utf-8");
}
</script>

<h3>Put your key here</h3>
<textarea id="key" cols="30" rows="2"></textarea>
<br>
<button onclick="genKey()">Generate  key</button>
<button onclick="savekey()">Save key</button>
<input type="file" id="keyToLoad" style="display:none;">
<button onclick="handleChooseKey();">Load key</button>
于 2013-05-03T09:55:31.467 回答