XMLHttpRequest file API
Table of Contents
FormData
使用 FormData
不需要 setRequestHeader("content-type", "application/x-www-form-urlencoded");
<form id="tfrom"> username: <input type="text" name="username"><br> age: <input type="text" name="age"><br> email: <input type="email" name="email"><br> <input type="button" value="ajax 发送" onclick="send();"> </form>
function send() { var fm = document.getElementById("tfrom"); var fd = new FormData(fm); var xhr = new XMLHttpRequest(); xhr.open("POST", "test.php", true); xhr.send(fd); // 发送表单 xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { document.getElementById("debug").innerHTML = xhr.responseText; } } } // 也可以直接 new 一个, 然后 新建 function send() { var fd_test = FormData(fm); fd_test.append("username", "username_test"); fd_test.append("email", "email_test"); fd_test.append("age", "age_test"); xhr.send(fd_test); }
file API
<input type="file" name="file_name" onchange="select_file();"> <div id="debug"></div>
function select_file() { var file = document.getElementsByTagName("input")[0].files[0]; var debug = document.getElementById("debug"); var cont = ""; cont += ‘文件名称: ‘ + file.name + "<br>"; cont += ‘文件大小: ‘ + file.size + "<br>"; debug.innerHTML = cont; }
jquery file api
var fd = new FormData(document.getElementById("fileinfo")); fd.append("CustomField", "This is some extra data"); $.ajax({ url: "stash.php", type: "POST", data: fd, processData: false, // 告诉 jQuery 不要去处理发送的数据 contentType: false // 告诉 jQuery 不要去设置 Content-Type 请求头 });
上传文件
<input type="file" name="file_name" onchange="select_file();"> <div id="debug"></div>
function select_file() { var myfile = document.getElementsByTagName("input")[0].files[0]; var fd = new FormData(); fd.append(‘myfile‘, myfile); var xhr = new XMLHttpRequest(); xhr.open(‘post‘, ‘test.php‘, true); xhr.send(fd); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { document.getElementById("debug").innerHTML = xhr.responseText; } } }
test.php
<?php echo ‘<pre>‘; print_r($_FILES); echo ‘</pre>‘;
从 FormData 中新建图片
function select_file() { var myfile = document.getElementsByTagName("input")[0].files[0]; var fd = new FormData(); fd.append(‘myfile‘, myfile); var xhr = new XMLHttpRequest(); xhr.open(‘post‘, ‘test.php‘, true); xhr.send(fd); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { document.getElementById("debug").innerHTML = xhr.responseText; } } // 显示图片 var img = document.createElement(‘img‘); img.src = window.URL.createObjectURL(myfile); document.getElementsByTagName("body")[0].appendChild(img); }
设置进度条
<input type="file" name="myfile" onchange="select_file();"> <div id="total" style="width: 500px; height: 50px; background: white; border: 1px solid green"> <div id="loaded" style="width: 0%; height: 100%; background: green;"></div> </div> <div id="debug"></div>
function select_file() { var myfile = document.getElementsByTagName("input")[0].files[0]; var fd = new FormData(); fd.append(‘myfile‘, myfile); var xhr = new XMLHttpRequest(); xhr.open(‘POST‘, ‘test.php‘, true); xhr.send(fd); xhr.upload.onprogress = function (event) { // console.log(event); if (event.lengthComputable) { // alert("loaded: " + event.loaded); // alert("total: " + event.total); // fd.size var loaded = event.loaded; var total = event.total; var percent = 100 * loaded / total; document.getElementById("loaded").style.width = percent + "%"; } } xhr.onload = function () { if (xhr.readyState == 4 && xhr.status == 200) { document.getElementById("debug").innerHTML = xhr.responseText; } } }
大文件切割
function select_file() { const length = 10 * 1024 * 1024; // 10 M var start = 0; var end = start + length; var myfile = document.getElementsByTagName("input")[0].files[0]; var total = myfile.size; var blob = new Blob(); var fd = new FormData(); while (start < total) { blob = myfile.slice(start, end); fd.append(‘file‘, blob); var percent = end/total * 100; document.getElementById("loaded").style.width = percent + ‘%‘; document.getElementById("loaded").innerHTML = percent + ‘%‘; var xhr = new XMLHttpRequest(); xhr.open("post", "test.php", false); // 使用同步, 异步可能出现包顺序错误 xhr.send(fd); start = end; end = start + length; if (end > total) { end = total; } } }
test.php
<?php $name = $_FILES[‘file‘][‘tmp_name‘]; $dest = ‘up/upload.txt‘; if (!file_exists($dest)) { move_uploaded_file($name, $dest); } else { file_put_contents($dest, file_get_contents($name), FILE_APPEND); }
一些 XMLHttpRequest 2 的 API
var xhr = new XMLHttpRequest(); xhr.upload.addEventListener("progress", progress, false); xhr.addEventListener("load", complete, false); xhr.addEventListener("error", failed, false); xhr.addEventListener("abort", canceled, false); xhr.open("POST", "test.php"); xhr.send(fd); function progress(event) { .... } function complete(event) { .... } function failed (event) { .... } function canceled(event) { .... }
XMLHttpRequest 2 还支持括跨域