<!DOCTYPE html>
<html>
<head>
<title>Html5 Ajax 上传文件</title>
</head>
<body>
<progress id="progressBar" value="0" max="100">
</progress>
<span id="percentage"></span>
<br />
<input type="file" id="file" name="Filedata" onchange="handleFiles(this)"/>
<input type="button" onclick="UpladFile()" value="submit" />
<div id="fileList" style="width:200px;height:200px;"></div>
<script type="text/javascript">
function handleFiles(obj){
var files = obj.files;
var img = new Image();
var reader = new FileReader();
reader.readAsDataURL(files[0]);
reader.onload = function(e){
alert(files[0].name + "," +e.total + " bytes");
img.src = this.result;
img.width = 200;
fileList.appendChild(img);
}
}
function UpladFile() {
var fileObj = document.getElementById("file").files[0]; // js 获取文件对象
// FormData 对象
var form = new FormData();
form.append("author", "hooyes"); // 可以增加表单数据
form.append("file", fileObj); // 文件对象
// XMLHttpRequest 对象
var xhr = new XMLHttpRequest();
xhr.open("post", "upload.php", true);
xhr.onload = function () {
alert("success");
};
xhr.upload.addEventListener("progress", progressFunction, false);
xhr.send(form);
}
function progressFunction(evt) {
var progressBar = document.getElementById("progressBar");
var percentageDiv = document.getElementById("percentage");
if (evt.lengthComputable) {
progressBar.max = evt.total;
progressBar.value = evt.loaded;
percentageDiv.innerHTML = Math.round(evt.loaded / evt.total * 100) + "%";
}
}
</script>
</body>
</html>
html5文件上传