如何上传HTML5文件?

时间:2013-02-15 04:08:20

标签: php jquery

由于某些奇怪的原因,以下代码在我上传文件时不打印任何内容。我认为HTML5 / jQuery会返回一些内容,但是当我打印出变量时,我没有得到任何回报。

<? 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> 

2 个答案:

答案 0 :(得分:0)

我建议使用Uplodify file upload plugin而不是太多代码,而且快速而简单。

答案 1 :(得分:0)

您可以使用jquery form docs 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/