Bogdan
Bogdan

Reputation: 1901

How can I get a file I selected in a file select control in file1.html, trough javascript, into file2.php to be processed

The structure looks like this:

<form>
...
some stuff
...
file select
...
some stuff
...
</form>

I need to send the input data from "file select" while not sending "some stuff" and as far as i've tried I couldn't get a form inside another form so that's not an option.

The way it works is like this: the file select control isn't displayed at first, clicking a button makes it show the control and some other stuff. I need a button to submit that file to be checked for different things (naming, size, etc) and uploaded to the server, without changing or reloading the rest of the window.

I could change the layout a bit and get the file select stuff out of the form but the boss doesn't want to change the design of the window and removing the outer-most form will be a lot of work as it's a very complicated part of the web site.

So, as the question says: Can I do it? Can I get the file trough javascript and send it to another php file for processing?

Upvotes: 0

Views: 60

Answers (1)

Treffynnon
Treffynnon

Reputation: 21553

The most browser compatible way to achieve this is to use a hidden iframe that you submit the form into. For example:

<iframe name="my_iframe" id="my_iframe" style="display: none;"></iframe>

<form action="/next_step.php" method="post" target="my_iframe" entype="multipart/form-data">
    <input type="file" name="file_upload" />
    <input type="button" id="upload_btn" value="Upload file" />

    <label for="name">Name</label>
    <input type="text" name="name" id="name" />

    <input type="submit" value="Next step" />
</form>

<script type="text/javascript">
    var btn = document.getElementById('upload_btn');
    btn.onclick = function(){
        var form_elem = document.forms[0];
        // direct file uploads through the hidden iframe
        form_elem.action = '/test_file.php';
        form_elem.target = 'my_iframe';

        // submit the form
        form_elem.submit();

        // now reset for next step in the form
        form_elem.action = '/next_step.php';
        form_elem.target = null;
    };
</script>

Upvotes: 1

Related Questions