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 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果