底层技术
用 Ajax 上传文件,使用的Javascript对象是 XMLHttpRequest2、FormData;发送给服务器端使用的 HTTP encode规范是 “multipart/form-data”,也就是普通的文件上传表单格式。
With XHR2, File upload through AJAX is supported. E.g. through FormData object, but unfortunately it is not supported by all/old browsers.
FormData support starts from following desktop browsers versions.
IE 10+
Firefox 4.0+
Chrome 7+
Safari 5+
Opera 12+
For more detail, see MDN link.
Code
File uploading requires the XMLHttpRequest2 object which is currently available in Firefox and Chrome.
检查是否是 XHR2 对象,可以看有没有方法 .upload 。
<form id="file-form" action="handler.php" method="POST">
<input type="file" id="file-select" name="photos[]" multiple/>
<button type="submit" id="upload-button">Upload</button>
</form>
var form = document.getElementById('file-form');
var fileSelect = document.getElementById('file-select');
var uploadButton = document.getElementById('upload-button');
form.onsubmit = function(event) {
event.preventDefault();
// Update button text.
uploadButton.innerHTML = 'Uploading...';
// Get the selected files from the input.
var files = fileSelect.files;
// Create a new FormData object.
var formData = new FormData();
// Loop through each of the selected files.
for (var i = 0; i < files.length; i++) {
var file = files[i];
// Check the file type.
if (!file.type.match('image.*')) {
continue;
}
// Add the file to the request.
formData.append('photos[]', file, file.name);
}
// Set up the request.
var xhr = new XMLHttpRequest();
// Open the connection. true=asynchronously
xhr.open('POST', '/upload', true);
// Set up a handler for when the request finishes.
xhr.onload = function () {
if (xhr.status === 200) {
// File(s) uploaded.
uploadButton.innerHTML = 'Upload';
} else {
alert('An error occurred!');
}
};
// Send the Data.
xhr.send(formData);
}
Ajax对象会发送 multipart/form-data post 请求给服务器端。
教程:
技术参考文档: