AJAX上传文件

 function up_files() {
var fileSelect = document.getElementById('file-select');
var files = fileSelect.files; var formData = new FormData(); for (var i = 0; i < files.length; i++) {
var file = files[i]; if (!file.type.match('image.*')) {
continue;
} formData.append('photos[]', file, file.name);
} var xhr = new XMLHttpRequest(); xhr.open('POST', 'test.php', true); xhr.onload = function () {
if (xhr.status !== 200) {
alert('An error occurred!');
}
}; var progressBar = document.getElementById('progress');
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
progressBar.value = (e.loaded / e.total) * 100;
progressBar.textContent = progressBar.value; // Fallback for unsupported browsers.
}
}; xhr.send(formData);
}
<div id="progress" style="width: 100px;height: 100px;background-color: #0baae4">Test content</div>
<input type="file" id="file-select" name="photos[]" multiple/>
<button onclick="up_files()">上传</button>

test.php 中使用$_FILES 来获取文件信息

原文链接:http://javascript.ruanyifeng.com/bom/ajax.html#toc21

上一篇:ajax原生


下一篇:js 常见弹出框学习