如何用 Ajax 上傳文件?

底層技術

用 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 請求給服務器端。

教程:

技術參考文檔:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章