文件上传

HTML部分:

<input type="file" id="id-input-file-3">

XMLHttpRequest Level 2添加了一个新的接口FormData,用来上传文件很好用。

 

JavaScript部分:(使用jquery)

var file = jQuery('#fileid').get(0).files[0]; // 得到文件
var formData = new FormData(); // 新建一个FormData对象
formData.append('file', file); // 
formData.append('uid', 123); // 向FormData对象添加字段
$.ajax({
    url:'/admin/ajax/fileuploadTmp',
    type:'POST',
    data: formData,
    success: function(data, status) {
    console.log(data);
    },
    processData: false,  // tell jQuery not to process the data
    contentType: false   // tell jQuery not to set contentType
});

 

如果不用jquery:


var oOutput = document.getElementById("output");
var oData = new FormData(document.forms.namedItem("fileinfo"));

  oData.append("CustomField", "This is some extra data");

  var oReq = new XMLHttpRequest();
  oReq.open("POST", "stash.php", true);
  oReq.onload = function(oEvent) {
    if (oReq.status == 200) {
      oOutput.innerHTML = "Uploaded!";
    } else {
      oOutput.innerHTML = "Error " + oReq.status + " occurred uploading your file.<br \/>";
    }
  };

  oReq.send(oData);

 

参考资料:

FormData - Web API 接口| MDN

使用FormData对象- Web 开发者指南| MDN

 

posted @ 2015-08-20 13:53  AminHuang  Views(206)  Comments(0Edit  收藏  举报