2014-07-14 72 views
0

我已经从阿贾克斯发送数据accessable传递数据未在PHP从阿贾克斯

HTML元素在这里给出

<input type="file" name="expansionfile" class="expansionfile" style="width:354px; margin:1px;" /> 

jQuery(document).ready(function(e) { 
         jQuery(".progress").hide(); 
         jQuery('.expansionfile').on('change',prepareUpload);   
        }); 

阿贾克斯元素在这里给出。我有jQuery文件获取onchange事件

function prepareUpload(event) 
        { 
         var file= event.target.files[0]; 
         //var file = this.files[0]; 
         jQuery(".progress").show(); 
         var bar = jQuery('.bar'); 
         var percent = jQuery('.percent'); 

         //var data = new FormData(); 
         //data.append('file',file); 
         //var data= {"file":file}; 
         formData = new FormData(); 
         formData.append('file', event.target[0].files[0]); 
         var data = formData; 
         //data = JSON.parse(data); 



         jQuery.ajax({ 
          url: '../wp-content/plugins/download-monitor/admin/extensionfile.php', 
          type: 'POST', 
          data:data, 
          cache: false, 
          enctype: 'multipart/form-data', 
          //dataType: 'json', 
          processData: false, 
          contentType: false, 
          success: function(data, textStatus, jqXHR) 
          { 
            console.log('success'); 
          }, 
          error:function(jqXHR, textStatus, errorThrown){ 
           console.log(errorThrown); 
          }, 
          complete:function(){ 
          }, 
          xhrFields: { 
           onprogress: function (progress, position, total, percentComplete) { 
           var percentage = Math.floor((progress.total/progress.totalSize) * 100); 
           var percentVal = percentage + '%'; 
           bar.width(percentVal) 
           percent.html(percentVal); 
           //console.log('progress', percentage); 
           if (percentage === 100) { 
            //console.log('DONE!'); 
           } 
           } 
          }, 
          processData: false, 
          contentType: file.type 
         }); 
        } 

这里的文件存储在文件变量。我可以在控制台中看到。

我已经在PHP

$filename = $_POST['file']; 
    var_dump($filename); 

接收数据,但它显示

Undefined index: file in C:\xampp\htdocs\apk2tpk\wp-content\plugins\download-monitor\admin\extensionfile.php 
+0

[This]( http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously-with-jquery)可能会有所帮助。你的表单是否有正确的enctype属性? – Alex

回答

0

我测试了我自己的机器上,我发现了,你必须从形式像访问文件这:e.target[0].files[0],然后在PHP中,你可以这样访问它:$_FILES['file']

formData = new FormData(); 
formData.append('file', event.target[0].files[0]); 
var data = formData; 
jQuery.ajax({ 
    url: '../wp-content/plugins/download-monitor/admin/extensionfile.php', 
    type: 'POST', 
    data: data, 
    cache: false, 
    processData: false, 
    contentType: false, 
    success: function(data){ 
     //do whatever you want 
    } 
}); 
+0

我已经定义了.. var data = {'file',file} –

+0

@MohaideenIsmail编辑我的答案 – Jonan

+0

它不适用于我 –