how to upload a file using javascript
Assuming you mean "In a browser" and "Without Flash/Java/Other plugins".
- Have the user select a file using a file input in a form.
- Call the submit method of the form object
e.g.
document.forms.myForm.submit();
If you want to do it without leaving the current page; set the target of the form to an iframe.
Don't forget to set the enctype.
You can't is the simple answer.
You could do it using a server-side language such as PHP, ColdFusion, ASP etc, and use Ajax to communicate with it and upload your file.
Here's a simple PHP tutorial and a ColdFusion tutorial as well
Hope the help you
Take a look at the AJAX toolkit (google it) and look at the asyncrhonus file upload control. You should get the code in the page source for your browser.
However, it might be a better idea to use controls defined for this in the language you are using because javascript is browser dependant. The Javascript found within the page source of the toolkit page IS broswer dependant, but is generate on the fly, so it can adapt, unlike normal Javascript.
If you're trying to ask how to do it AJAX-style, i.e. without navigating away from the page, the answer lies in using iframe
s. There are several examples of this if you google for it, but here's one to get you started: http://www.webtoolkit.info/ajax-file-upload.html
The problem is that you can't upload a file via a regular AJAX form, so you have to make the browser submit the form properly. This is done by submitting the form in a hidden iframe
instead.
Of course you should make sure the form works (though with a page refresh) when JavaScript is disabled. This is called "progressive enhancement" and is always a good idea.
The actual target of the form must of course be a script that is capable of handling the file upload, but this is true with JavaScript and without. JS being client-side, it can't (and shouldn't!) write to the server directly.