dtrphb5597
dtrphb5597
2013-10-15 12:06
浏览 59

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

图片转代码服务由CSDN问答提供 功能建议

首先,我搜索了很多关于这个的主题,我不想使用任何插件。

  function addToDatabase(menuItem){
 var formData = new FormData(); 
 formData.append(“Description”,document.getElementById(“DescriptionID”)。value); \  n 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,\  n success:function(result){
 $(“#PageContent”)。html(result); 
} 
}); 
} 
   
 
 

Js函数发送到服务器的东西。 虽然在服务器端代码 $ _ POST ['Description'] 有值,但是 $ _ FILES ['file-0'] 没有。 \ n

 &lt; input type =“file”id =“filesID”name =“files []”multiple /&gt; 
&lt; textarea id =“DescriptionID”rows =“5”cols =“53”  &gt;&lt; / textarea&gt; 
   
 
 

HTML部分代码。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongyi6269
    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

    点赞 评论

相关推荐