dtrphb5597 2013-10-15 12:06
浏览 94
已采纳

使用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. 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.

  • 写回答

1条回答 默认 最新

  • dongyi6269 2013-10-15 12:20
    关注

    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
    xhr.send(fd);
    

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

    hope that helps

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog