Javascript: Uploading a File... Without a File

Javascript: Uploading a file... without a file

Why not just use XMLHttpRequest() with POST?

function beginQuoteFileUnquoteUpload(data)
{
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://www.mysite.com/myuploadhandler.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function ()
{
if (xhr.readyState == 4 && xhr.status == 200)
alert("File uploaded!");
}
xhr.send("filedata="+encodeURIComponent(data));
}

The handler script at the server just writes the file data to a file.

EDIT
File upload is still a http post with a different content type. You can use this content type and separate your content with boundaries:

function beginQuoteFileUnquoteUpload(data)
{
// Define a boundary, I stole this from IE but you can use any string AFAIK
var boundary = "---------------------------7da24f2e50046";
var xhr = new XMLHttpRequest();
var body = '--' + boundary + '\r\n'
// Parameter name is "file" and local filename is "temp.txt"
+ 'Content-Disposition: form-data; name="file";'
+ 'filename="temp.txt"\r\n'
// Add the file's mime-type
+ 'Content-type: plain/text\r\n\r\n'
+ data + '\r\n'
+ boundary + '--';

xhr.open("POST", "http://www.mysite.com/myuploadhandler.php", true);
xhr.setRequestHeader(
"Content-type", "multipart/form-data; boundary="+boundary

);
xhr.onreadystatechange = function ()
{
if (xhr.readyState == 4 && xhr.status == 200)
alert("File uploaded!");
}
xhr.send(body);
}

If you want to send additional data, you just separate each section with a boundary and describe the content-disposition and content-type headers for each section. Each header is separated by a newline and the body is separated from the headers by an additional newline. Naturally, uploading binary data in this fashion would be slightly more difficult :-)

Further edit: forgot to mention, make sure whatever boundary string isn't in the text "file" that you're sending, otherwise it will be treated as a boundary.

Reading Files In JavaScript Without Uploading Them

You can use the JavaScript FileReader object to read the contents of a file the user selects.

The user will first have to select a file, like if they would want to upload it, and then you can use that information to read the contents of that file.

There are a few nice examples here about how to do that with similar use cases.

File upload with Javascript without user intervention

You can't do this without under intervention, this would he a huge security hole. Think about visiting a webpage and it being able to grab and upload any of your files without you doing a thing...you can see how this would be abused really fast.

You might be able to do this with a Firefox extension, I'm not sure of the security limitations it imposes (though I wouldn't be surprised if it disallowed this as well), but JavaScript would not be an option here.



Related Topics



Leave a reply



Submit