Get filename from input [type='file'] using jQuery

前端 未结 11 995
陌清茗
陌清茗 2020-12-23 20:15

This is the uploaded form.

相关标签:
11条回答
  • 2020-12-23 20:28

    Getting the file name is fairly easy. As matsko points out, you cannot get the full file path on the user's computer for security reasons.

    var file = $('#image_file')[0].files[0]
    if (file){
      console.log(file.name);
    }
    
    0 讨论(0)
  • 2020-12-23 20:29

    This was a very important issue for me in order for my site to be multilingual. So here is my conclusion tested in Firefox and Chrome.

    jQuery trigger comes in handy.

    So this hides the standard boring type=file labels. You can place any label you want and format anyway. I customized a script from http://demo.smarttutorials.net/ajax1/. The script allows multiple file uploads with thumbnail preview and uses PHP and MySQL.

    <form enctype="multipart/form-data" name='imageform' role="form"    ="imageform" method="post" action="upload_ajax.php">
        <div class="form-group">
            <div id="select_file">Select a file</div>
            <input class='file' type="file" style="display: none " class="form-control" name="images_up" id="images_up" placeholder="Please choose your image">
            <div id="my_file"></div>
            <span class="help-block"></span>
        </div>
        <div id="loader" style="display: none;">
            Please wait image uploading to server....
        </div>
        <input type="submit" value="Upload" name="image_upload" id="image_upload" class="btn"/>
    </form>
    
    $('#select_file').click(function() {
        $('#images_up').trigger('click');
        $('#images_up').change(function() {
            var filename = $('#images_up').val();
            if (filename.substring(3,11) == 'fakepath') {
                filename = filename.substring(12);
            } // Remove c:\fake at beginning from localhost chrome
            $('#my_file').html(filename);
       });
    });
    
    0 讨论(0)
  • 2020-12-23 20:39
    $("#filetosend").prop('files')[0]
    
    0 讨论(0)
  • 2020-12-23 20:43

    You can access to the properties you want passing an argument to your callback function (like evt), and then accessing the files with it (evt.target.files[0].name) :

    $("document").ready(function(){
      $("main").append('<input type="file" name="photo" id="upload-photo"/>');
      $('#upload-photo').on('change',function(evt) {
        alert(evt.target.files[0].name);
      });
    });
    
    0 讨论(0)
  • 2020-12-23 20:45

    If selected more 1 file:

    $("input[type="file"]").change(function() {
       var files = $("input[type="file"]").prop("files");
       var names = $.map(files, function(val) { return val.name; });
       $(".some_div").text(names);
    });
    

    files will be a FileList object. names is an array of strings (file names).

    0 讨论(0)
提交回复
热议问题