Automatically Selecting File and Submitting, Javascript

前端 未结 3 1068
攒了一身酷
攒了一身酷 2021-01-28 21:08

So I am trying to programmatically browse and I want to upload a file to an input tag with the type of file.

How would I go about this? I don\'t want the user to have to

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-28 21:28

    You can't have your script browse the user's machine and automatically search for a file you think they want to submit - but you can have your form submit when they find the file they want to give you:

    That will generate a "Browse" button next to the field which, when the user clicks it, will open an OS explorer window to select their file.

    Example form:

    From there, simply place an onchange event listener on the field to automatically submit your form. With JQuery it looks like this:

    $(function(){
        $('#my_file').change(function(){
           $('#my_form').submit();
        }); 
    
        $('#my_form').submit(function(event){
            alert('form submitted');
        });
    });
    

    Working demo: http://jsfiddle.net/AlienWebguy/SZFfL/

提交回复
热议问题