本文實例為大家分享了php+ajax 文件上傳的具體代碼,供大家參考,具體內容如下
html 代碼
1
2
3
4
5
|
< form action = "{pboot:form fcode=8}" method = "post" id = "t" enctype = "multipart/form-data" > < input type = "file" name = 'tables_a' id = "tables" onchange = "abs()" > < input type = "hidden" name = 'tables' id = 'tables_2' > < input type = "submit" value = "提交" > </ form > |
項目使用的是pbootCMS 所以地址可忽略
enctype="multipart/form-data"因為設計到文件上傳必須在from 表單中添加該屬性
js代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
function abs(){ var fileArray = document.getElementById( 'tables' ).files[0]; var formData = new FormData(); formData.append( "fileArray" , fileArray) $.ajax({ url: "{pboot:httpurl}/api.php/Tables/index" , //傳向后臺服務器文件 type: 'POST' , //傳遞方法 data: formData, //傳遞的數據 dataType : 'json' , //傳遞數據的格式 async: false , //這是重要的一步,防止重復提交的 cache: false , //設置為false,上傳文件不需要緩存。 contentType: false , //設置為false,因為是構造的FormData對象,所以這里設置為false。 processData: false , //設置為false,因為data值是FormData對象,不需要對數據做處理。 success: function (responseStr){ if (responseStr.code != 0){ alert( '上傳成功' ); $( '#tables_2' ).val( '{pboot:httpurl}' +responseStr.data); } else { alert( '上傳失敗' ); } }, error: function () { alert( "上傳錯誤!" ); } }); } |
PHP代碼
1
2
3
4
5
6
7
8
9
10
11
12
|
public function index() { $name = $_FILES [ 'fileArray' ][ 'name' ]; $last = substr ( $name , strrpos ( $name , '.' )); $name = date ( 'YmdHis' ).rand(10000,99999). $last ; $address = ROOT_PATH. '/upload/' . $name ; if (move_uploaded_file( $_FILES [ 'fileArray' ][ 'tmp_name' ], $address )){ return json(1, '/upload/' . $name ); } else { return json(0); } } |
$_FILES['fileArray']['tmp_name'] 是文件的臨時存儲位置,所以直接將他移動過去就好了
以上所述是小編給大家介紹的php+ajax的文件上傳詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:https://www.cnblogs.com/CcPz/p/10168433.html