Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

AJAX upload

Status
Not open for further replies.

germallon

Programmer
Jun 26, 2008
1
US
Hello all,

Short Version:
How can I upload a file asynchronously using a XHR object??
***********************************


Long Version:
I am trying to upload files to my server using AJAX. I cannot use regular html forms, since I want to be able to upload large files (exceeding 5 GB in some cases), thus it is imperative to do it asynchronously using the PUT method, as opposed as the traditional POST and GET methods.

The problem is that when I use a regular form element, I can only access restricted properties of that object (name, value, type) but I do not know how to access the data inside the file itself. (see below).

The code below will successfully create a file w/ the appropriate name in the server. Unfortunately it copies an empty file.



Thank you in advance for any help..

~G.

-----------------------------------------------------------

<html><head>

<script type="text/javascript" >

var xmlHttp;
function HandleFile (form) {
var file = form.uploadedFile; //get file element
var filename = file.value;
xmlHttp=new XMLHttpRequest();

if(xmlHttp!=null){
xmlHttp.onreadystatechange=function(){
if((xmlHttp.readyState==4)&&(xmlHttp.status == 200)){
alert("File Uploaded");
}
}
xmlHttp.open("PUT",'path/in/the/server/' + filename , true);
xmlHttp.setRequestHeader('Content-type', 'text/plain');
xmlHttp.send(file);
}
}

</script>


</head>
<body>
<form name="putform" id="putform" onsubmit="return HandleFile(this);">
Upload File <input type="file" id="uploadedFile" name="uploadedFile" />'
<input type="submit" name="submit" value="Upload File"/>
</form>
</body>
</html>

---------------------------------------------------------------
 
var file = form.uploadedFile; //get file element

Get a handle on the form element and store it in a variable called "file".

xmlHttp.send(file);

Send the handle to the form element to the server.

I'd suggest that what you want to do is send the file to the server rather than the handle to the form element. Unfortunately there is no easy way to do file-system access in Javascript.

There are a couple of freebie flash-upload scripts floating around that seem to do a reasonable job of uploading large files.

[sub]Never be afraid to share your dreams with the world.
There's nothing the world loves more than the taste of really sweet dreams.
[/sub]

Webflo
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top