今天在wordpress后台管理的插件管理界面,想添加一个ajax无刷新的上传,然后折腾了一下午,对于一个干前端的来说真心是惭愧呀!
好的,先说一下思路: 上传文件,必需得取得当前的文件的数据流,然后通过ajax的post方式发送给服务器处理。
(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));}