ajax文件上传特定的输入数量

时间:2012-08-24 01:41:24

标签: php ajax upload

<form class="imagegen_file" enctype="multipart/form-data" action="/image_maker/file">
<input class="file" name="image_0" type="file">
<input class="file" name="image_1" type="file">
<input class="file" name="image_2" type="file">
<input class="file" name="image_3" type="file">
<input .....
</form>

<a onclick="return image_gen_file();">upload</a>

<script type="text/javascript">
function image_gen_file(){
    var data = new FormData();
    jQuery.each($('.file')[0].files, function(i, file) {
        data.append('image_'+i, file);
    });

    $.ajax({
        url: baseurl + "/image_maker/file",
        data: data,
        cache: false,
        contentType: false,
        processData: false,
        type: 'POST',
        success: function(data){
            alert(data);
        }
    });

}</script>
上面代码文件上传的人只适用于第一个输入(“image_0”)我想让它适用于所有其他人我怎么能这样做?

2 个答案:

答案 0 :(得分:0)

你只是在第一个input上循环。你需要一个嵌套循环:

var data = new FormData();

$('.file').each(function(i) {
    $.each(this.files, function(j) {
        data.append('image_' + i + '_' + j, this);
    });
});

如果您想将它们分别发布在自己的AJAX帖子中,请改用:

$('.file').each(function() {

    var data = new FormData();

    jQuery.each(this.files, function(i, file) {
        data.append('image_'+i, file);
    });

    $.ajax({
        url: baseurl + "/image_maker/file",
        data: data,
        cache: false,
        contentType: false,
        processData: false,
        type: 'POST',
        success: function(data) {
            alert(data);
        }
    });
});

答案 1 :(得分:0)

var data = new FormData();
$('.file').each(function(i) {
    data.append('file'+i, this.files[0]);
});
$.ajax({
    url: baseurl + "/image_maker/file",
    data: data,
    cache: false,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function(data) {
        alert(data);
    }
});