如何使用 URL.createObjectURL 获取本地文件名?

The*_*lob 5 javascript image object

createObjectURL用来获取图像的属性,例如宽度和高度。如何获取本地文件名?

loadURL = function (event) {
    var output = document.getElementById('myimage'),
        output.src = URL.createObjectURL(event.target.files[0]);
    output.onload = function () {

        document.getElementById("urlinput").value = output. ? ? ? ? ?

        document.getElementById("width").value = output.width;
        document.getElementById("height").value = output.height;
    }
}
Run Code Online (Sandbox Code Playgroud)

你如何从中获取文件名?我曾尝试filenamesrcname。我知道我可以从相应的值中获取值,input type="file"但我想从对象中获取它(上面的输出。???????),但是如何?

Ath*_*ace 4

URL.createObjectURL最终返回值中没有任何该信息。它返回一个字符串类型的 URL。默认情况下,您的元素也不会img,但如果您event.target是文件类型的输入,您可以从中获取文件名。

loadURL = function (event) {
    var output = document.getElementById('myimage'),
        output.src = URL.createObjectURL(event.target.files[0]),
        fileName = event.target.files[0].name;
    output.onload = function () {

        document.getElementById("urlinput").value = output. ? ? ? ? ?

        document.getElementById("width").value = output.width;
        document.getElementById("height").value = output.height;
    }
}
Run Code Online (Sandbox Code Playgroud)

小提琴: http: //jsfiddle.net/AtheistP3ace/h1pswvk1/

小提琴代码

HTML:

<input id="test" type="file" />
Run Code Online (Sandbox Code Playgroud)

JS:

document.getElementById('test').addEventListener('change',
    function (event) {
        alert(event.target.files[0].name);
    }
);
Run Code Online (Sandbox Code Playgroud)

编辑:抱歉,我想我错过了您说您知道可以从输入中获取它的最后一部分。不管怎样,如果你的document.getElementById('myimage')img 标签没有文件名。唯一的选择是,如果src有 url 来解析它,但从你的代码来看,标签似乎img存在,但src直到将文件添加到输入然后src以编程方式设置时才存在。如果我错了,请纠正。您为什么不想从可用的地方获取它?为什么只从myimage元素呢?