如何使用FormData()jquery提交动态文件类型并在php中接收它

时间:2016-12-06 13:01:34

标签: php jquery multipartform-data form-data

对于单个文件上传,它工作正常,请参阅下面的示例

<input name="audio_preview" id="audio_preview" type="file">

var formData = new FormData();
var audio_preview = document.getElementById('audio_preview');
var audio_preview_file = audio_preview.files[0];
formData.append('audio_preview', audio_preview_file);

现在在php

中收到它
[audio_preview] => Array
     (
       [name] => bawa_sus-bawa_sus-10511_hifi.mp3
       [type] => audio/mpeg
       [tmp_name] => /customers/4/6/d/domain.com/tmp/phpUTkVgr
       [error] => 0
       [size] => 116737
      )

上面的代码工作正常,但现在我想提交动态文件输入字段,请查看下面的代码

<input name="download_files[]" type="file">
<input name="download_files[]" type="file">
<input name="download_files[]" type="file">
<input name="download_files[]" type="file">

<script>
var allFiles = jQuery("input[name='download_files[]']");
 jQuery.each(allFiles,function(index, value){
    formData.append('download_files[]', value.files[0]);
 });
</script>

它发送到数组

[download_files] => Array
        (
            [name] => Array
                (
                    [0] => ajax-loader.gif
                    [1] => already-subscribed-help.gif
                )

            [type] => Array
                (
                    [0] => image/gif
                    [1] => image/gif
                )

            [tmp_name] => Array
                (
                    [0] => /customers/4/6/d/domain.com/tmp/phpnd9czo
                    [1] => /customers/4/6/d/domain.com/tmp/phpNC4BlI
                )

            [error] => Array
                (
                    [0] => 0
                    [1] => 0
                )

            [size] => Array
                (
                    [0] => 19110
                    [1] => 7805
                )
          )
 )

AJAX

$.ajax({
            type: 'post',
            url: $form.attr('action'),
            data: formData,
            processData: false, // Don't process the files
            contentType: false,
            success: function(s) {
                alert('files uploaded');
                jQuery( '.wordpress-ajax-form' ).each(function(){
                    this.reset();
                });
                jQuery("#sucess").show().delay(4000).fadeOut();
            },
            error: function(xhr) {
                alert("An error occured files uploaded: " + xhr.status + " " + xhr.statusText);
            }
        });

如何使用jQuery使用FormData()提交文件。

1 个答案:

答案 0 :(得分:0)

将上面的脚本标记中的jQuery代码替换为

<script>
 jQuery.each($('input[name^="download_files"]')[0].files, function(i, file) {
     formData.append('download_files[]', file);
 });
</script>