//图片上传
function uploadImg(fileId){
1,创建新的formData对象用append方法逐个添加键值对。
var fd = new FormData(); |
2 | fd.append("name", "志文工作室"); |
3 | fd.append("blog", "http://lzw.me"); |
4 | fd.append("file", document.getElementById("file")); |
FormData发送请求:
1 | var xhr = new XMLHttpRequest(); |
2 | xhr.open("POST" ,"http://lzw.me" , true); |
3 | xhr.send(fd); |
4 | xhr.onload = function(e) { |
5 | if (this.status == 200) { |
6 | alert(this.responseText); |
7 | } |
8 | }; |
jquery中formDat使用方法:
01 | $.ajax({ |
02 | url: "http://lzw.me", |
03 | type: 'POST', |
04 | data: fd, |
05 | /** |
06 | *必须false才会自动加上正确的Content-Type |
07 | */ |
08 | contentType:false, |
09 | /** |
10 | * 必须false才会避开jQuery对 formdata 的默认处理 |
11 | * XMLHttpRequest会对 formdata 进行正确的处理 |
12 | */ |
13 | processData:false |
14 | }).done(function(result){ |
15 | console.log(result); |
16 | }).fail(function(err){ |
17 | console.log(err); |
18 | }); |
使用PHP一个完整的事例,表达formData的异步刷新
01 | <?php |
02 | //php 接收表单提交信息并打印 |
03 | if( isset( $_REQUEST['do']) ){ |
04 | var_dump($_REQUEST); |
05 | var_dump($_FILES); |
06 | die(); |
07 | } |
08 |
09 | ?> |
10 | <!DOCTYPE HTML> |
11 | <html> |
12 | <head> |
13 | <meta charset="utf-8"> |
14 | <title>FormData Test - lzw.me</title> |
15 | <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> |
16 | </head> |
17 | <body> |
18 | <form id="form"> |
19 | <input type="file" name="file" id="file" /> |
20 | <input type="text" name="name" id="" value="志文工作室" /> |
21 | <input type="text" name="blog" id="" value="http://lzw.me" /> |
22 | <input type="submit" name="do" id="do" value="submit" /> |
23 | </form> |
24 | <script> |
25 | $("form").submit(function(e){ |
26 | e.preventDefault(); |
27 | |
28 | //空对象然后添加 |
29 | var fd = new FormData(); |
30 | fd.append("name", "志文工作室"); |
31 | fd.append("blog", "http://lzw.me"); |
32 | fd.append("file", document.getElementById("file")); |
33 | //fd.append("file", $(":file")[0].files[0]); //jQuery 方式 |
34 | fd.append("do", "submit"); |
35 | |
36 | //通过表单对象创建 FormData |
37 | var fd = new FormData(document.getElementById("form")); |
38 | //var fd = new FormData($("form:eq(0)")[0]); //jquery 方式 |
39 | |
40 | //XMLHttpRequest 原生方式发送请求 |
41 | var xhr = new XMLHttpRequest(); |
42 | xhr.open("POST" ,"" , true); |
43 | xhr.send(fd); |
44 | xhr.onload = function(e) { |
45 | if (this.status == 200) { |
46 | alert(this.responseText); |
47 | }; |
48 | }; |
49 | return; |
50 | //jQuery 方式发送请求 |
51 | $.ajax({ |
52 | type:"post", |
53 | //url:"", |
54 | data: fd, |
55 | processData: false, |
56 | contentType: false |
57 | }).done(function(res){ |
58 | console.log(res); |
59 | }); |
60 | |
61 | return false; |
62 | }); |
63 | </script> |
64 | </body> |
65 | </html> |
}
本文介绍了如何使用JavaScript和FormData对象实现图片上传功能,并详细解释了相关代码逻辑及原理。
1956

被折叠的 条评论
为什么被折叠?



