如何使用javascript、jquery-ajax在更改<input type'file'>时获取所选文件的完整路径?

2024-04-25 13:24:55 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在使用<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变量包含所选文件的only name,而不是full path
我在网上搜索过,但出于安全原因,浏览器(FF、chrome)似乎只需给出文件名即可。
是否有其他方法获取所选文件的完整路径?


Tags: 文件text路径idinputvartypescript
3条回答

出于安全原因,浏览器不允许这样做,即浏览器中的JavaScript无法访问文件系统,但是使用HTML5文件API,只有Firefox提供了一个mozFullPath属性,但是如果您试图获取该值,它将返回一个空字符串:

$('input[type=file]').change(function () {
    console.log(this.files[0].mozFullPath);
});

http://jsfiddle.net/SCK5A/

所以不要浪费你的时间。

编辑:如果需要文件的路径来读取文件,可以使用FileReaderAPI代替。这里有一个相关的问题:Preview an image before it is uploaded.

试试这个:

它将为您提供一个临时路径,而不是准确的路径,如果您希望显示所选的图像,可以使用此脚本,如本jsfiddle示例中所示(通过选择图像和其他文件进行尝试):-

JSFIDDLE

代码如下:

HTML格式:

<input type="file" id="i_file" value=""> 
<input type="button" id="i_submit" value="Submit">
<br>
<img src="" width="200" style="display:none;" />
<br>
<div id="disp_tmp_path"></div>

JS:-

$('#i_file').change( function(event) {
    var tmppath = URL.createObjectURL(event.target.files[0]);
    $("img").fadeIn("fast").attr('src',URL.createObjectURL(event.target.files[0]));

    $("#disp_tmp_path").html("Temporary Path(Copy it and try pasting it in browser address bar) --> <strong>["+tmppath+"]</strong>");
});

这不完全是你想要的,但也许它可以帮助你某处。

您不能这样做-出于安全考虑,浏览器将不允许这样做。

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>

相关问题 更多 >