如何用 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 请求给服务器端。

教程:

技术参考文档:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值