做英文网站多钱/怎样做网站卖自己的产品
如今,使用AJAX实际上可以上传文件。是的,AJAX,不是像swf或java那样蹩脚的AJAX。
(它还包括拖放界面,但很容易被忽略。)
基本上它归结为:document.getElementById('files').addEventListener('change', function(e) {
var file = this.files[0];
var xhr = new XMLHttpRequest();
(xhr.upload || xhr).addEventListener('progress', function(e) {
var done = e.position || e.loaded var total = e.totalSize || e.total;
console.log('xhr progress: ' + Math.round(done/total*100) + '%');
});
xhr.addEventListener('load', function(e) {
console.log('xhr upload complete', e, this.responseText);
});
xhr.open('post', '/URL-HERE', true);
xhr.send(file);});
所以它基本上归结为这是=)xhr.send(file);
另一种(更好的IMO)方式是使用FormData。这允许您1)命名文件,如在表单中,2)发送其他东西(文件),如在表单中。var fd = new FormData;fd.append('photo1', file);fd.append('photo2', file2);fd.append('other_data', 'foo bar');xhr.send(fd);
FormData 使服务器代码更清晰,更向后兼容(因为请求现在具有与普通表单完全相同的格式)。
所有这些都不是实验性的,而是非常现代的。Chrome 8+和Firefox 4+知道该怎么做,但我不知道其他任何人。
这是我在PHP中处理请求(每个请求1个图像)的方式:if ( isset($_FILES['file']) ) {
$filename = basename($_FILES['file']['name']);
$error = true;
// Only upload if on my home win dev machine
if ( isset($_SERVER['WINDIR']) ) {
$path = 'uploads/'.$filename;
$error = !move_uploaded_file($_FILES['file']['tmp_name'], $path);
}
$rsp = array(
'error' => $error, // Used in JS
'filename' => $filename,
'filepath' => '/tests/uploads/' . $filename, // Web accessible
);
echo json_encode($rsp);
exit;}