0

我需要你的帮助。

我想设计一个javascript函数,这样当我调用它时,它会打开一个对话框,要求我导航到选定的文件,一旦我点击“打开”按钮,它就会将文件的路径保存到一个变种。

你怎么做到这一点?我不喜欢 input type="file" 方法,因为我不需要那个特定的输入出现在我的页面上。

IE:

function getlocation() {
var x = popup the open file dialog box and let the user select a file
}
4

1 回答 1

2

允许用户选择文件的唯一方法是使用<input type="file" />1。您不必让此元素可见,只需在页面上即可。

当用户选择一个文件时,您所能得到的只是它的名称。你无法得到它的路径。另外,请注意文件上传元素是异步的。您需要使用onchange事件(回调)来获取名称。

您可以使用 隐藏上传元素display: none,然后让另一个 JavaScript 函数以编程方式触发它。(注意:此方法不适用于 Opera,可能还有其他浏览器。已在 Chrome、Firefox 和 IE 8/9 中测试过)

<style>
    #getFile{
        display: none;
    }
</style>

<input type="file" id="getFile" />
<button id="openFile" type="button">Click Me</button>

<script>
    var uploadElement = document.getElementById('getFile'),
        uploadTrigger = document.getElementById('openFile'),
        openFileUpload = function(){
            uploadElement.click();
        },
        alertValue = function () {
            alert(uploadElement.value);
        };

    if (window.addEventListener) {
        uploadTrigger.addEventListener('click', openFileUpload);
        uploadElement.addEventListener('change', alertValue);
    } else {
        uploadTrigger.attachEvent('onclick', openFileUpload);
        uploadElement.attachEvent('onchange', alertValue);
    }
</script>

演示: http: //jsfiddle.net/rJA7n/3/show(编辑:http: //jsfiddle.net/rJA7n/3/

在大多数浏览器(包括 Opera)中应该工作的另一种方法是使文件上传元素“不可见”并在其顶部放置一个元素。因此,当您单击您认为是按钮的内容时,您实际上是在单击上传元素。AJAX 上传器(如http://fineuploader.com/)使用此方法允许您“样式化”上传按钮。

<style>
    #getFile{
        width: 100px;
        opacity: 0;
        filter: alpha(opacity = 0);
    }

    #openFile{
        display: inline;
        margin-left: -100px;
        background-color: red;
        height: 30px;
        width: 100px;
        padding: 10px;
        color: white;
        text-align: center;
    }
</style>

<input type="file" id="getFile" />
<div id="openFile">Click Me</div>

<script>
    var uploadElement = document.getElementById('getFile'),
        alertValue = function(){
            alert(uploadElement.value);
        };

    if(window.addEventListener){
        uploadElement.addEventListener('change', alertValue);
    }
    else{
        uploadElement.attachEvent('onchange', alertValue);
    }
</script>

演示: http: //jsfiddle.net/cKGft/4/show/(编辑:http: //jsfiddle.net/cKGft/4/

1好吧,如果你想真正花哨,你可以使用拖放。我在这里做了一个快速演示:http: //jsfiddle.net/S6BY8/2/show(编辑:http: //jsfiddle.net/S6BY8/2/

于 2013-04-12T17:42:54.617 回答