最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Data not appending to FormData Object - Stack Overflow

programmeradmin4浏览0评论

I'm trying to upload multiple images for an image upload system using AJAX on Jquery.

However, I'm having trouble getting the FormData object to take in the data from the file input. Here is my code:

HTML:

<form id="multiform" role="form" action="process.php" method="post" enctype="multipart/form-data">
    <div class="form-group">
        <div class="">
            <label for="picture">Upload Pictures</label>
            <input type="file" id="pic_upload_file" name="pics[]" multiple>
            <input type="button" id="pic_upload" name="pic_upload" value="Upload">
        </div>
    </div>
</form>

JQuery

$('#pic_upload').click(function(e) {
    var formData = new FormData();
    formData.append("pics", file);
}); 

This object is created and I can see it in the console, but I dont know how to get the user file input data into it to send to a php script.

Can anyone help?

I'm trying to upload multiple images for an image upload system using AJAX on Jquery.

However, I'm having trouble getting the FormData object to take in the data from the file input. Here is my code:

HTML:

<form id="multiform" role="form" action="process.php" method="post" enctype="multipart/form-data">
    <div class="form-group">
        <div class="">
            <label for="picture">Upload Pictures</label>
            <input type="file" id="pic_upload_file" name="pics[]" multiple>
            <input type="button" id="pic_upload" name="pic_upload" value="Upload">
        </div>
    </div>
</form>

JQuery

$('#pic_upload').click(function(e) {
    var formData = new FormData();
    formData.append("pics", file);
}); 

This object is created and I can see it in the console, but I dont know how to get the user file input data into it to send to a php script.

Can anyone help?

Share Improve this question edited Jun 29, 2017 at 8:45 linktoahref 8,0023 gold badges32 silver badges53 bronze badges asked Sep 17, 2014 at 15:35 MobazMobaz 5953 gold badges11 silver badges26 bronze badges 1
  • What exactly is in your file variable? – leopik Commented Sep 17, 2014 at 15:41
Add a ment  | 

1 Answer 1

Reset to default 2

You have a file input that takes multiple files, so you have to get those files and append each one to the formData object

$('#pic_upload').on('click', function(e) {
    var formData = new FormData(),
        files    = $('#pic_upload_file').get(0).files;

    $.each(files, function(i, file) {
        formData.append("pics_"  + i, file); 
    });

    $.ajax({
        url         : 'test.php',
        data        : formData,
        contentType : false,
        processData : false,
        type        : 'POST'
    });

}); 
发布评论

评论列表(0)

  1. 暂无评论