如何在javascript上发送文件

How send file on javascript?

本文关键字:文件 javascript      更新时间:2023-09-26
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.

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

可能吗?

有谁知道怎么做?

是的,你可以,但这并不容易。诀窍是使用 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等的服务器端脚本来处理。