0
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);

我需要更改photo文件内容的 URL

./DirectoryImage/imagetest.jpg

并发送文件内容

./DirectoryImage/imagetest.jpg

upload_url

但我不知道如何upload_url在javascript中发送文件的内容......

可能吗?

有谁知道怎么做?

4

1 回答 1

3

是的,你可以,但这并不容易。诀窍是使用FileReader对象。这是我放在一起的一些示例代码,用于在将图像放入<div>.

我很确定您可以对任何文件执行相同的操作,只要您可以根据FileReader用户输入的任何内容创建对象。

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);
};

MDN 页面对整个主题非常有帮助,例如FileReader对象 API。

另外,我似乎记得浏览器对通常的嫌疑人(IE6-7等)的支持很差。


值得一提的是,这很困难,因为出于安全目的,浏览器中的 Javascript 并非旨在与服务器通信。Javascript 通常只是客户端。文件传输等通常应该使用 PHP、Perl、Ruby 等中的服务器端脚本来处理。

于 2013-09-27T05:46:09.830 回答