Steven Matthews
Steven Matthews

Reputation: 11285

Automatically Selecting File and Submitting, Javascript

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 input any data, but to instead go after a predefined file.

Upvotes: 0

Views: 6025

Answers (3)

SeanCannon
SeanCannon

Reputation: 77966

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:

<input type="file" name="my_file" />

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:

<form name="form" id="my_form">
    <input type="file" id="my_file" name="my_file" />
</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/

Upvotes: 1

Yahia
Yahia

Reputation: 70369

this is NOT possible since it would be a real security flaw - see http://www.w3.org/TR/html4/interact/forms.html#file-select

Upvotes: 0

mrk
mrk

Reputation: 5117

This is not possible. For <input type=file>, the value attribute of the input element is READONLY with Javascript. Otherwise, that would be a large security hole.

Upvotes: 0

Related Questions