【问题标题】:How can I get the seletced filename from file button?如何从文件按钮获取选定的文件名?
【发布时间】:2016-03-04 02:18:51
【问题描述】:

我想尝试使用链接来触发隐藏的输入文件按钮,但单击链接后我想获取所选文件。

css

{#upload {display:none;}}

jQuery

$(".file-image").on('click', function(e){
    e.preventDefault();
    $("#upload:hidden").trigger('click');
   console.log($("#upload"));             
});

html:

<a href="#" class="file-image">Add image</a>';
<input id="upload" type="file"/>';

如何获取上传按钮的选定文件名的值?

在控制台中我看到那个对象就像

[input#fileupload, context:document, selector: "#upload"]
[0]: input#upload
...
...

value: c:\temp\file.jpg //and this value seems to be correct
...

我试过$("#upload")[0]['value']

【问题讨论】:

    标签: jquery html css file-upload


    【解决方案1】:

    你可以用这个:

    $("#upload")[0].files;
    

    【讨论】:

    • 哦,谢谢!你回答了我要找的东西,但是有没有办法检索路径?
    • 没有。用户决定将文件存储在他们自己的文件系统上的位置不是任何 web 应用程序都需要知道的。
    • 我需要预览所选图片的完整路径。
    • @bestprogrammerintheworld — 不,你没有。 stackoverflow.com/questions/4459379/…(另见xyproblem.info
    • 好的,我知道@Mohd Abdul Mujib 的回答是我可以使用 readURL() 但我没有管理代码按预期工作。非常感谢!
    【解决方案2】:

    你需要的是FileReader()对象的readAsDataURL方法。

    这是我用过的功能,你可以绘制参考...

            function readURL(input) {
    
                num = jQuery(input).attr("data-opti");
                if (input.files && input.files[0]) {
                    var reader = new FileReader();
                    reader.onload = function (e) {
    
                        jQuery('#preview' + num).attr('src', e.target.result);
                        var logoHeight = jQuery('#preview' + num).height();
                        if (logoHeight < 104) {
                            var margintop = (104 - logoHeight) / 2;
                            jQuery('#preview' + num).css('margin-top', margintop);
                        }
                    }
    
                    reader.readAsDataURL(input.files[0]);
                } else {
                  // no files selected it seems
                }
            }
            jQuery(".imageinput").change(function () {
                readURL(this);
            });
    

    这可用于在文件上传之前显示图像的预览,因此它是增强用户体验的一个非常漂亮的功能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-18
      • 2019-12-16
      • 2012-11-08
      • 2020-06-27
      • 1970-01-01
      • 2021-09-26
      • 1970-01-01
      相关资源
      最近更新 更多