Page 1 of 1

Upload file without submit form

Posted: Tue Dec 16, 2008 6:38 am
by clix99
Hi,
This is a little tricky, i hope i can explain it properly:

In order to let my user upload files from my site i use 2 file:
1. file.html
2. upload_file.php

On file.html i have the following input inside a from:
<input type="file" id="file">

This is to let the user select the file.


On the uploading page - upload_file.php i use this element:
$_FILES["file"]
To receive the information from the file input and upload the file. - This is after the user clicked submit on the html page.

So far so good.

Now, How can i upload a file without submitting the form?
I would like to let the user choose a file and stay on the same page while the upload is taking place and not to use the traditional submit form method.
(you probably guessed I'm going to use ajax).

I did some research and i think i now what information I'm missing, if i got it right:

I need to get the value of a file input:
document.getElementByID('file').value
And send it as a query string to the uploading file (with xmlhttprequest):

"upload_file.php?path=" + document.getElementByID('file').value

If this is indeed the way, My question is:
What do i need to write on upload_file.php so that the file will be uploaded using the information from a query string and not a form?


If the solution i came up with is wrong please let me know how this can be done some other way?

Re: Upload file without submit form

Posted: Tue Dec 16, 2008 11:41 am
by kaszu
It's wrong, sorry. If you could download to the server any file by only its name, then it would be huge security threat.
What you need to do is create an iframe (outside viewport if you don't want your users to see it) and change form target to an id of the iframe.
Pressing "Send" form will submit the file to the "upload_file.php" inside iframe and page will not refresh.

Code: Select all

<iframe id="my_iframe" style="position: absolute; left: -1000px; top: -1000px;" src="about&#058;blank"></iframe>
<form method="post" enctype="multipart/form-data" action="upload_file.php" target="my_iframe">
    <input type="file" name="file" />
</form>