2013-02-15 100 views
0

由於一些奇怪的原因,當我上傳文件時,以下代碼不會打印出任何內容。我認爲HTML5/jQuery會返回一些東西,但是當我打印出我的變量時,我沒有收到任何迴應。如何上傳HTML5文件?

<? print_r($_FILES) ?> 
<? print_r($_POST) ?> 
<? print_r($_GET) ?> 
<? print_r($_REQUEST) ?> 
<form enctype="multipart/form-data" action="/upload.php" 
method="post" class="putImages"> 
    <input name="media[]" type="file" multiple/> 
    <input class="button" type="submit" alt="Upload" value="Upload" /> 
</form> 

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
<script> 
$(function() { 
var data = new FormData($('input[name^="media"]'));  
jQuery.each($('input[name^="media"]')[0].files, function(i, file) { 
    data.append(i, file); 
}); 

$(':file').on('change', function() { 
$.ajax({ 
    type: 'POST', 
    data: data, 
    url: 'http://localhost/upload.php', 
    cache: false, 
    contentType: false, 
    processData: false, 
    success: function(data){ 
     alert(data); 
    } 
}); 
}); 
}); 
</script> 
+1

哦,有可以做這件事庫的數量。使用它們(或者至少查看源代碼)而不是實現自己的解決方案。他們還提供了進度條樣式AJAX上傳 – Yang 2013-02-15 04:12:34

+0

使用此庫https://github.com/blueimp/jQuery-File-Upload ... – AlphaMale 2013-02-15 04:18:41

回答

0

您可以使用jquery form文檔http://malsup.com/jquery/form/

一個簡單的演示代碼,如:

$(document).ready(function() { 
    var options = { 
     target:  '#output2', // target element(s) to be updated with server response 
     beforeSubmit: showRequest, // pre-submit callback 
     success:  showResponse // post-submit callback 

     // other available options: 
     //url:  url   // override for form's 'action' attribute 
     //type:  type  // 'get' or 'post', override for form's 'method' attribute 
     //dataType: null  // 'xml', 'script', or 'json' (expected server response type) 
     //clearForm: true  // clear all form fields after successful submit 
     //resetForm: true  // reset the form after successful submit 

     // $.ajax options can be used here too, for example: 
     //timeout: 3000 
    }; 

    // bind to the form's submit event 
    $('#myForm2').submit(function() { 
     // inside event callbacks 'this' is the DOM element so we first 
     // wrap it in a jQuery object and then invoke ajaxSubmit 
     $(this).ajaxSubmit(options); 

     // !!! Important !!! 
     // always return false to prevent standard browser submit and page navigation 
     return false; 
    }); 
}); 

這裏是例子http://malsup.com/jquery/form/file/