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);
我需要更改文件内容上的照片
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 等服务器端脚本来处理。
关于javascript - 如何在javascript上发送文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19043333/