close
轉自 http://wbkuo.pixnet.net/blog/post/209781556
--
參考文章: http://abandon.ie/notebook/simple-file-uploads-using-jquery-ajax
測試程式碼:
01.
<?php
02.
// ajax 呼叫
03.
if
(isset(
$_POST
[
'upload_form'
]))
04.
{
05.
echo
"<pre>_FILES = "
. print_r(
$_FILES
, TRUE).
"</pre>"
;
06.
}
07.
// 一般 form submit
08.
elseif
(isset(
$_FILES
) &&
$_FILES
)
09.
{
10.
echo
json_encode(
$_FILES
);
11.
return
;
12.
}
13.
?>
14.
<meta http-equiv=
"content-type"
content=
"text/html; charset=utf-8"
>
15.
<script src=
"https://code.jquery.com/jquery-1.12.2.js"
></script>
16.
<script>
17.
var
ajax_upload =
18.
{
19.
files : [],
20.
21.
init :
function
()
22.
{
23.
var
_self = this;
24.
25.
// 綁定檔案變更時的處理
26.
$(
'input[type=file]'
).on(
'change'
,
function
(event) {_self.prepareUpload(event); });
27.
28.
// 上傳
29.
$(
'#upload_ajax'
).bind(
'click'
,
function
(event)
30.
{
31.
_self.upload(event);
32.
});
33.
},
34.
35.
prepareUpload :
function
(event)
36.
{
37.
this.files = event.target.files;
38.
console.log(this.files);
39.
},
40.
41.
upload :
function
()
42.
{
43.
console.log(
'files = '
, this.files);
44.
45.
var
data =
new
FormData();
46.
$.each(this.files,
function
(key, value)
47.
{
48.
data.append(key, value);
49.
});
50.
51.
$.ajax(
52.
{
53.
url :
'ajax_post_file.php'
,
54.
type :
'POST'
,
55.
data : data,
56.
cache : false,
57.
dataType :
'json'
,
58.
processData : false,
59.
contentType : false,
60.
success:
function
(data, textStatus, jqXHR)
61.
{
62.
console.log(
'upload success!!'
);
63.
},
64.
error:
function
(jqXHR, textStatus, errorThrown)
65.
{
66.
console.log(
'ERRORS: '
+ textStatus);
67.
}
68.
});
69.
}
70.
};
71.
72.
$(
function
()
73.
{
74.
ajax_upload.init();
75.
});
76.
</script>
77.
<form method=
"post"
enctype=
"multipart/form-data"
>
78.
<input type=
"file"
name=
'photo'
id=
'photo'
>
79.
<button id=
'upload_form'
name=
'upload_form'
type=
'submit'
>form 上傳</button>
80.
<button id=
'upload_ajax'
name=
'upload_ajax'
type=
'button'
>ajax 上傳</button>
81.
</form>
--
全站熱搜
留言列表