html 代碼
1 <form action="{pboot:form fcode=8}" method="post" id="t" enctype="multipart/form-data"> 2 <input type="file" name='tables_a' id="tables" onchange="abs()"> 3 <input type="hidden" name='tables' id='tables_2'> 4 <input type="submit" value="提交"> 5 </form>
項目使用的是pbootCMS 所以地址可忽略
enctype="multipart/form-data"因為設計到文件上傳必須在from 表單中添加該屬性
js代碼
1 function abs(){ 2 var fileArray = document.getElementById('tables').files[0]; 3 var formData = new FormData(); 4 formData.append("fileArray", fileArray) 5 $.ajax({ 6 url: "{pboot:httpurl}/api.php/Tables/index",//傳向后台服務器文件 7 type: 'POST', //傳遞方法 8 data: formData, //傳遞的數據 9 dataType : 'json', //傳遞數據的格式 10 async:false, //這是重要的一步,防止重復提交的 11 cache: false, //設置為false,上傳文件不需要緩存。 12 contentType: false,//設置為false,因為是構造的FormData對象,所以這里設置為false。 13 processData: false,//設置為false,因為data值是FormData對象,不需要對數據做處理。 14 success: function (responseStr){ 15 if(responseStr.code != 0){ 16 alert('上傳成功'); 17 $('#tables_2').val('{pboot:httpurl}'+responseStr.data); 18 }else{ 19 alert('上傳失敗'); 20 } 21 }, 22 error: function () { 23 alert("上傳錯誤!"); 24 } 25 }); 26 }
PHP代碼
1 public function index() 2 { 3 $name = $_FILES['fileArray']['name']; 4 $last = substr($name,strrpos($name,'.')); 5 $name = date('YmdHis').rand(10000,99999).$last; 6 $address = ROOT_PATH.'/upload/'.$name; 7 if(move_uploaded_file($_FILES['fileArray']['tmp_name'],$address)){ 8 return json(1,'/upload/'.$name); 9 }else{ 10 return json(0); 11 } 12 }
$_FILES['fileArray']['tmp_name'] 是文件的臨時存儲位置,所以直接將他移動過去就好了
轉載請說明出處謝謝!!!