如何在javascript上发送文件?

var photo = 'http://cs323230.vk.me/u172317140/d_5828c26f.jpg';
var upload_url = 'http://cs9458.vk.com/upload.php?act=do_add&mid=62..';

var xmlhttp = getXmlHttp();
var params = 'photo=' + encodeURIComponent(photo);
xmlhttp.open("POST", upload_url, true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4) {
        if(xmlhttp.status == 200) {
            var answer2 = xmlhttp.responseText;
            console.log(answer2);
            alert(answer2);
        }
    }
};
xmlhttp.send(params);

I need to change the photo URL on the contents of the file

./DirectoryImage/imagetest.jpg

and send contents of the file

./DirectoryImage/imagetest.jpg

on upload_url.

But I don't know how send the contents of the file on upload_url in javascript...

Is it possible?

Does anyone know how make it?

Yes, you can, but it's not easy. The trick is using the FileReader object. Here's some sample code I put together for uploading an image after it's dropped into a <div>.

I'm pretty sure you can do the same with any file, as long as you can make the FileReader object from whatever your user inputs.

YourNamespace.uploadImg = function(evt) {
    // Get the first file, if a stack of files has been dropped
    // (to transfer the whole stack just repeat the process)
    var file = evt.dataTransfer.files[0]; 

    // Make a FileReader object
    var reader = new FileReader();

    // Build an AJAX request to send the file once the browser has received it.
    // The FileReader will call this onload event when it's finished.
    reader.onload = function(evtLoad) {
        var req = new XMLHttpRequest();
        req.open('POST', '/foo/bar.php', true);
        req.onreadystatechange = function() {
            if (req.readyState == 4 && req.status == 200) {
                alert("success");
            }
        };

        // Encode the file stream properly, set the appropriate header, and send.
        var params = "foo=bar&data=" + encodeURIComponent(evtLoad.target.result);

        req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        req.send(params);
    };

    // This starts the whole process: read in the file as a data URL.
    // When it's finished it calls the onload() that was defined above.
    reader.readAsDataURL(file);
};

The MDN pages are very helpful on this whole topic, such as the FileReader object API.

Also I seem to remember browser support is poor for the usual suspects (IE6-7, etc).


It's worth mentioning that this is difficult because Javascript in browsers was not designed to talk to the server, for security purposes. Javascript is usually client-side only. File transfers and such should usually be handled with a server-side script in PHP, Perl, Ruby, etc.