無刷新文件上傳是一個常見而又有點復雜的問題,常見的解決方案是構造 iframe 方式實現。
在 HTML5 中提供了一個 FormData 對象 API,通過 FormData 可以方便地構造一個表單請求,并通過 XMLHttpRequest 來發送。通過 FormData 對象發送文件也是可以的,如此則無刷新上傳就變的非常簡單了。
那么 FormData 怎么使用呢?下面武林網對此進行簡單的介紹。
1. 構造 FormData 對象
想得到一個FormData對象,很簡單:
var fd = new FormData();
FormData 對象只提供了一個方法 append ,用于向對象中添加表單請求參數。
在當前主流瀏覽器中,可通過如下兩種方式獲取或修改FormData。
方法一:創建一個空的FormData對象,然后再用append方法逐個添加鍵值對。示例:
var fd = new FormData();fd.append("name", "商業源碼網");fd.append("blog", "http://www.49028c.com");fd.append("file", document.getElementById("file"));
這種方法可以不需要 HTML 的表單對象存在。
方法二:取得form元素對象,將它作為參數傳入FormData對象中。示例:
var formobj = document.getElementById("form");var fd = new FormData(formobj);
當然,這里還可以使用 append 方法繼續向 fd 中添加其他參數。
2. FormData 發送請求
得到 FormData 對象了,如何發送請求呢? FormData 對象主要用于增強型的 XMLHttpRequest 對象的 send 方法中。參考如下示例:
var xhr = new XMLHttpRequest(); xhr.open("POST" ,"http://www.49028c.com" , true);xhr.send(fd);xhr.onload = function(e) { if (this.status == 200) { alert(this.responseText); }};
3. jquery 中使用 FormData
在 jQuery 的 ajax 方法中,也可使用 FormData 方式實現無刷新上傳。但要注意參數的設置,參考如下:
$.ajax({ url: "http://www.49028c.com", type: 'POST', data: fd, /** *必須false才會自動加上正確的Content-Type */ contentType:false, /** * 必須false才會避開jQuery對 formdata 的默認處理 * XMLHttpRequest會對 formdata 進行正確的處理 */ processData:false}).done(function(result){ console.log(result);}).fail(function(err){ console.log(err);});
4. 一個完整的示例(包含PHP處理示例):
<?php//php 接收表單提交信息并打印if( isset( $_REQUEST['do']) ){ var_dump($_REQUEST); var_dump($_FILES); die();}?><!DOCTYPE HTML><html> <head> <meta charset="utf-8"> <title>FormData Test - www.49028c.com</title> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> </head> <body> <form id="form"> <input type="file" name="file" id="file" /> <input type="text" name="name" id="" value="商業源碼網" /> <input type="text" name="blog" id="" value="http://www.49028c.com" /> <input type="submit" name="do" id="do" value="submit" /> </form> <script> $("form").submit(function(e){ e.preventDefault(); //空對象然后添加 var fd = new FormData(); fd.append("name", "商業源碼網"); fd.append("blog", "http://www.49028c.com"); fd.append("file", document.getElementById("file")); //fd.append("file", $(":file")[0].files[0]); //jQuery 方式 fd.append("do", "submit"); //通過表單對象創建 FormData var fd = new FormData(document.getElementById("form")); //var fd = new FormData($("form:eq(0)")[0]); //jquery 方式 //XMLHttpRequest 原生方式發送請求 var xhr = new XMLHttpRequest(); xhr.open("POST" ,"" , true); xhr.send(fd); xhr.onload = function(e) { if (this.status == 200) { alert(this.responseText); }; }; return; //jQuery 方式發送請求 $.ajax({ type:"post", //url:"", data: fd, processData: false, contentType: false }).done(function(res){ console.log(res); }); return false; }); </script> </body></html>
新聞熱點
疑難解答