2013-10-15 12:06

使用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);


    type: "POST",
    url: "dbAdder.php",
    data: formData,
    cache: false,
    contentType: false,
    processData: false,
    success: function(result){

Js function that sending to server things. While in the server-side code $_POST['Description'] have value, but $_FILES['file-0'] doesnt.

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

HTML part of code.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • dongyi6269 dongyi6269 8年前

    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.

    it's pure javascript, and deals well with file uploads.

    BUT- note that it's not supported by all browsers, see here: 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

    here's a very nice tutorial for further use of xhr2: http://www.html5rocks.com/en/tutorials/file/xhr2/

    hope that helps

    点赞 9 评论 复制链接分享