Tags

,

In this blog I’m writing about how to upload multiple files using Varien_File_Uploader.

Currently I’d been working on a banner module where multiple files had to be uploaded. For that my html structure look likes:

<div class="entry-edit">
    <div class="entry-edit-head">
        <h4 class="icon-head head-edit-form fieldset-legend">Images</h4>
    </div>
    <div class="fieldset">
        <div class="hor-scroll">
            <table class="form-list container">
                <tr class="wrapper-tr">
                    <td class="value">
                        <input type="file" name="images[]"/>
                    </td>
                    <td class="label">
                        <span class="remove">Remove</span>
                    </td>
                </tr>
            </table>
            <input type="button" class="add" value="Add Image"/>
        </div>
    </div>
</div>

And a script to add more

<script>
    jQuery(document).ready(function() {
        jQuery('.add').click(function() {
            var wrapper = "<tr class='wrapper-tr'>" +
                    "<td class='value'><input type='file' name='images[]'></td>" +
                    "<td class='label'><span class='remove'>Remove</span></td>" +
                    "</tr>";
            jQuery(wrapper).find('.remove').on('click', function() {
                jQuery(this).parent('.wrapper-tr').remove();
            });
            jQuery(wrapper).appendTo('.container');
        });
        jQuery('.container').on('click', 'span.remove', function() {
            if (jQuery('.wrapper-tr').length > 1) {
                jQuery(this).parents('.wrapper-tr').remove();
            } else {
                alert('at least one image need to be selected');
            }
        });
    });
</script>

In order to be able to upload all file selected by user/admin which are available in images[] use the code written below in your controller’s saveAction()

$uploader = new Varien_File_Uploader(
        array(
    'name' => $_FILES['images']['name'][$key],
    'type' => $_FILES['images']['type'][$key],
    'tmp_name' => $_FILES['images']['tmp_name'][$key],
    'error' => $_FILES['images']['error'][$key],
    'size' => $_FILES['images']['size'][$key]
        )
);

You can see more at stackoverflow

Advertisements