1. 程式人生 > >js檔案上傳以及表單提交

js檔案上傳以及表單提交

原理:

    使用 FormData物件,將要傳送給後臺的資料 都 append該物件中,包括檔案,最後將這個物件傳送給後臺。

<!doctype html><html lang="zh">
<head> <meta charset="utf-8"> <title>HTML5 Ajax Uploader</title> <script src="jquery.js"></script></head>
<body> <p> <input
type="file" id="upfile"> </p> <p> <input type="button" id="upJS" value="用原生JS上傳"> </p> <p> <input type="button" id="upJQuery" value="用jQuery上傳"> </p> <script> /*原生JS版*/ document.getElementById("upJS").onclick
= function () { /* FormData 是表單資料類 */ var fd = new FormData(); //建立一個表單物件 var ajax = new XMLHttpRequest(); fd.append("upload", 1); //將資料append 到表單物件中 /* 把檔案新增到表單裡 */ fd.append("upfile", document.getElementById("upfile").files[0]); ajax.open
("post", "/messagefile", true); //提交方式 介面地址 同步非同步? ajax.setRequestHeader("token","11111"); // 設定 請求頭 ajax.onload = function () { console.log("準備完畢"); console.log(ajax.responseText); console.log(fd); };
ajax.send(fd); //傳送 ajax請求 上傳檔案
ajax.onreadystatechange = function () { if (ajax.readyState == 4 && ajax.status == 200) { //步驟五 如果能夠進到這個判斷 說明 資料 完美的回來了,並且請求的頁面是存在的 console.log(ajax.responseText);//輸入相應的內容 } }
}
/* jQuery 版 */ $('#upJQuery').on('click', function () { var fd = new FormData(); fd.append("upload", 4); fd.append("upfile", $("#upfile").get(0).files[0]); fd.append("Headers",000);
$.ajax({ url: "/messagefile", type: "POST", processData: false, contentType: false, headers:{ token:"555" }, data: fd, success: function (d) { console.log(d); } }); }); </script></body>
</html>