本文實(shí)例為大家分享了ajax實(shí)現(xiàn)無刷新上傳文件功能的具體代碼,供大家參考,具體內(nèi)容如下
詳細(xì)代碼如下
!DOCTYPE HTML> html> head> meta http-equiv="Content-Type" content="text/html; charset=utf-8"> title>ajax無刷新上傳文件/title> script> window.onload = function(){ var oBtn = document.getElementById('btn'); var oMyFile = document.getElementById('myFile'); oBtn.onclick = function() { //alert(oMyFile.value); //獲取到的是file控件的value值,這個(gè)內(nèi)容是顯示給你看的文字,不是我們選擇的文件 //oMyFile.files file控件中選擇的文件列表對(duì)象 //alert(oMyFile.files); //我們是要通過ajax把oMyFile.files[0]數(shù)據(jù)發(fā)送給后端 /* for (var attr in oMyFile.files[0]) { console.log( attr + ' : ' + oMyFile.files[0][attr] ); } */ //利用ajax發(fā)送必須要有一個(gè)ajax對(duì)象 var xhr = new XMLHttpRequest(); //監(jiān)聽上傳事件 xhr.onload = function(){ //alert(1); //alert(this.responseText);//后端返回的數(shù)據(jù) var d = JSON.parse(this.responseText); alert(d.msg + ' : ' + d.url); //顯示上傳成功 并且顯示文件路徑 } xhr.open('post','post_file.php',true); //open打開的方式不能使用get,上傳文件的地址,使用異步上傳 //在使用post發(fā)送的時(shí)候必須要帶一些請(qǐng)求頭信息 xhr.setRequestHeader('X-Request-With', 'XMLHttpRequest'); //send要發(fā)送數(shù)據(jù) //將要上傳的數(shù)據(jù)轉(zhuǎn)換成二進(jìn)制數(shù)據(jù) //那么必須知道后端接收當(dāng)前文件的名稱是什么 然后后面帶上當(dāng)前文件的數(shù)據(jù) var oFormData = new FormData(); //通過FormData來構(gòu)建提交數(shù)據(jù) oFormData.append('file',oMyFile.files[0]); xhr.send(oFormData); } } /script> /head> body> input type="file" id="myFile" />input type="button" id="btn" value="上傳" /> /body> /html>
后端php代碼post_file.php
?php header('Content-type:text/html; charset="utf-8"'); $upload_dir = 'uploads/'; if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){ exit_status(array('code'=>1,'msg'=>'錯(cuò)誤提交方式')); } if(array_key_exists('file',$_FILES) $_FILES['file']['error'] == 0 ){ $pic = $_FILES['file']; if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){ exit_status(array('code'=>0,'msg'=>'上傳成功','url'=>$upload_dir.$pic['name'])); } } echo $_FILES['file']['error']; exit_status(array('code'=>1,'msg'=>'出現(xiàn)了一些錯(cuò)誤')); function exit_status($str){ echo json_encode($str); exit; } ?>
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
標(biāo)簽:營(yíng)口 內(nèi)江 本溪 玉樹 遼寧 銅川 四川 益陽
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《ajax實(shí)現(xiàn)無刷新上傳文件功能》,本文關(guān)鍵詞 ajax,實(shí)現(xiàn),無,刷新,上傳,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。