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 微信小程序web-view嵌套H5页面IOS左滑会出现相同的页面,有什么解决方法吗?
  • ¥60 如何批量获取json的url
  • ¥15 comsol仿真压阻传感器
  • ¥15 Python线性规划函数optimize.linprog求解为整数
  • ¥15 llama3中文版微调
  • ¥15 pg数据库导入数据序列重复
  • ¥15 三分类机器学习模型可视化分析
  • ¥15 本地测试网站127.0.0.1 已拒绝连接,如何解决?(标签-ubuntu)
  • ¥50 Qt在release捕获异常并跟踪堆栈(有Demo,跑一下环境再回答)
  • ¥30 python,LLM 文本提炼