(1)如何获取当前文件的数据流呢?
答:通过FormData()实例化的对象,将文件数据append在一个变量里面
(2)如何获取数据?
答:在type为file的input表单中,自带一个files属性。
HTML页面发送文件上传请求:
<input type="file" name="upload_img" id='upload_img'/> <img src="" id='myfile_img' alt='' title='' width='300'/> <script type="text/javascript"> var uploadImg = document.getElementById('upload_img'); var myfileImg = document.getElementById('myfile_img'); uploadImg.onchange = function() { var imgName = this.files[0].name; //let reader = new FileReader(); var fordata = new FormData(); fordata.append('my_file',this.files[0]); //向服务器发送文件数据 ajaxPost(fordata,function(obj){ var content = JSON.parse(obj.response); console.log(content); if(content.status == 'sucess'){ myfileImg.src = './images/'+imgName; } }); } function ajaxPost(data,fn) { var xhr = new XMLHttpRequest(); xhr.open('post','./upload.php','true'); xhr.send(data); xhr.onload = function() { fn(this); } } </script>
服务器处理文件数据,生成上传的文件:
$success = array('status' => 'sucess', 'code' => '1'); $error = array('status' => 'error', 'code' => '0'); if (!empty($_FILES)) { $file = $_FILES['my_file']; $new_file_dir = dirname(__FILE__) . '/images/' . $file['name']; @move_uploaded_file($file['tmp_name'], $new_file_dir); exit(json_encode($success)); } else { exit(json_encode($error)); }