如何获得文件的完整路径,同时选择文件使用<input type= ' file ' >

<input type="file" id="fileUpload">
<script type="text/javascript">
function getFilePath(){
     $('input[type=file]').change(function () {
         var filePath=$('#fileUpload').val(); 
     });
}
</script>

但是filePath var只包含所选文件的名称,而不是完整的路径。 我在网上搜索了一下,但似乎出于安全原因,浏览器(FF,chrome)只给出了文件的名称。 是否有其他方法获得所选文件的完整路径?


当前回答

一个有趣的提示:虽然这在网上是不可用的,如果你在Electron中使用JS,那么你可以这样做。

使用标准的HTML5文件输入,您将在所选文件上收到一个额外的path属性,其中包含真正的文件路径。

完整的文档在这里:https://github.com/electron/electron/blob/master/docs/api/file-object.md

其他回答

你不能这样做——出于安全考虑,浏览器不允许这样做。

When a file is selected by using the input type=file object, the value of the value property depends on the value of the "Include local directory path when uploading files to a server" security setting for the security zone used to display the Web page containing the input object. The fully qualified filename of the selected file is returned only when this setting is enabled. When the setting is disabled, Internet Explorer 8 replaces the local drive and directory path with the string C:\fakepath\ in order to prevent inappropriate information disclosure.

和其他

你错过了);这是在change事件函数的末尾。

也不要为change事件创建函数,而是像下面这样使用它,

<script type="text/javascript">

    $(function()
    {
        $('#fileUpload').on('change',function ()
        {
            var filePath = $(this).val();
            console.log(filePath);
        });
    });

</script>

你可以使用下面的代码来获取上传文件的本地URL:

<script type="text/javascript">    
    var path = (window.URL || window.webkitURL).createObjectURL(file);
    console.log('path', path);
</script>

这对我来说是个可行的解决方案

const path = (window.URL || window.webkitURL).createObjectURL(file);

它将返回一个blob URL以本地访问该文件。

可以,如果你可以选择上传整个文件夹的话

<input type="file" webkitdirectory directory multiple/>

更改事件将包含:

.target.files[...].webkitRelativePath: "FOLDER/FILE.ext"

但它不包含整个绝对路径,只包含相对路径。Firefox也支持。

可以使用FileReader API更改img元素的src。

https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL