简体   繁体   English

使用Ajax上传文件 - FormData

[英]Upload files with Ajax - FormData

First of all, i search in many many topics about that and i dont want to use any plugins. 首先,我搜索了许多关于这个的主题,我不想使用任何插件。

function addToDatabase(menuItem){
  var formData = new FormData();
  formData.append("Description", document.getElementById("DescriptionID").value);
  jQuery.each($('#filesID')[0].files, function(i, file) {
      formData.append('file-'+i, file);
  });

  $.ajax({

    type: "POST",
    url: "dbAdder.php",
    data: formData,
    cache: false,
    contentType: false,
    processData: false,
    success: function(result){
      $("#PageContent").html(result);
    }
  });
}

Js function that sending to server things. Js函数发送到服务器的东西。 While in the server-side code $_POST['Description'] have value, but $_FILES['file-0'] doesnt. 虽然在服务器端代码$_POST['Description']有值,但是$_FILES['file-0']没有。

<input type="file" id="filesID" name="files[]" multiple />
<textarea id="DescriptionID" rows="5" cols="53"></textarea>

HTML part of code. HTML部分代码。

if you are planning to upload files, it complicates it all a little bit. 如果你打算上传文件,它会让它变得复杂一点。

if external plugin is not an option, i highly suggest using XHR2. 如果外部插件不是一个选项,我强烈建议使用XHR2。

it's pure javascript, and deals well with file uploads. 它是纯粹的JavaScript,并且处理文件上传。

BUT- note that it's not supported by all browsers, see here: http://caniuse.com/xhr2 但请注意,并非所有浏览器都支持它,请访问: http//caniuse.com/xhr2

// prepare xhr object
var xhr = new XMLHttpRequest();

xhr.open('POST', 'dbAdder.php', true);

// upload complete handler
xhr.onload = function(e){
if (this.status == 200) {
    //
}
    else { // }
};

// upload progress handler
xhr.upload.onprogress = function(e) {
    if (e.lengthComputable) {
            // e.total, e.loaded
    }
};

var fd = new FormData();
fd.append("file", file);
fd.append("Description", 'description text');
fd.append("field2", 'value2');

// send the xml http request
xhr.send(fd);

here's a very nice tutorial for further use of xhr2: http://www.html5rocks.com/en/tutorials/file/xhr2/ 这是一个非常好的教程,可以进一步使用xhr2: http ://www.html5rocks.com/en/tutorials/file/xhr2/

hope that helps 希望有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM