How to use your own form with blueimp jquery-file-uploader

While working on a frontend image uploader for a WP site I’m having an issue … I had gotten everything working with the “basic plus” demo form and code.
However, I need to be able to customize the way the form looks / acts so I’ve changed the frontend a bit and have tried changing the jQuery as needed …
but, I’m still a bit new to JS and am having trouble getting some stuff working.

Here’s the issue that I’m running into when I submit the form, after submitting the form the uploader processes the first file but aborts any that follow …
when I look at what uploaded though, for the title I get some kind of id (example “1391778237-0526”) and than in place of the file type I get the “multipart/form databoundary–”.

What my media library looks like after trying to upload a few times: The bottom three are from before I tried changing the upload form the rest are from after I made my changes.

My HTML form


<form id="fileupload" action="" method="POST" enctype="multipart/form-data">

	<p class="upload-categorize">Select an Event to Categorize your Upload under</p>
						
	<?php
	$event_query_args = array(
		'post_type' => 'event',
		'posts_per_page' => 5
	);

	$event_query = new WP_Query( $event_query_args );
	
         if ( $event_query->have_posts() ) { ?>
		<select class="categorize-options" name="event_name">
			<?php while ( $event_query->have_posts() ) : $event_query->the_post(); ?>
									
				<option><?php the_title(); ?>&nbsp;&nbsp;|&nbsp;&nbsp;<?php echo get_the_date(); ?></option>

			<?php endwhile; wp_reset_postdata(); ?>
		</select>
	<?php } else { ?>
		<select class="categorize-options">
			<option>OOPS! It appears we're fresh out of events!</option>
		</select>
	<?php } ?>

	<button type="button" class="btn" id="pick-photos"><?php _e( "Select Photos to Upload", "shorti" ); ?></button>
	<input type="file" id="upload-file" name="photos[]" multiple />

	<ul id="files" class="files">
		<!-- The file uploads will be shown here -->
	</ul>

	<button name="upload" id="upload" class="btn upload"><?php _e("Upload", "shorti"); ?></button>
	<p class="terms-link">Please make sure to read<br />our <a href="<?php echo site_url(); ?>/terms-and-usage">Terms & Usage</a> page</p>

	<div id="progress" class="progress">
		<div class="progress-bar progress-bar-success"></div>
	</div>
</form>

JS form processor


jQuery.noConflict();

jQuery( function() {

	"use strict";

	jQuery('#pick-photos').click( function() {
		jQuery('#upload-file').click();
	});

	var url = 'http://url/to/UploadHandler.php';

    jQuery('#fileupload').fileupload({
        url: url,
        dataType: 'json',
        autoUpload: false,
        //acceptFileTypes: /(\\.|\\/)(gif|jpe?g|png)jQuery/i,
        maxFileSize: 5000000, // 5 MB
        // Enable image resizing, except for Android and Opera,
        // which actually support image resizing, but fail to
        // send Blob objects via XHR requests:
        disableImageResize: /Android(?!.*Chrome)|Opera/
            .test(window.navigator.userAgent),
        previewMaxWidth: 100,
        previewMaxHeight: 100,
        previewCrop: false
    }).on('fileuploadadd', function (e, data) {
        data.context = jQuery('<div/>').appendTo('#files');
        jQuery.each(data.files, function (index, file) {
            var node = jQuery('<p/>').append(jQuery('<span/>').text(file.name));
            if (!index) {
                node
            }
            node.appendTo(data.context);

            jQuery('#upload').off('click').on('click', function() {
                data.formData = jQuery('#fileupload').serializeArray();
                data.submit();
                return false;
            });
        });
    }).on('fileuploadprocessalways', function (e, data) {
        var index = data.index,
            file = data.files[index],
            node = jQuery(data.context.children()[index]);
        if (file.preview) {
            node
                .prepend('<br>')
                .prepend(file.preview);
        }
        if (file.error) {
            node
                .append('<br>')
                .append(jQuery('<span class="text-danger"/>').text(file.error));
        }
    }).on('fileuploadprogressall', function (e, data) {
        var progress = parseInt(data.loaded / data.total * 100, 10);
        jQuery('#progress .progress-bar').css(
            'width',
            progress + '%'
        );
    }).on('fileuploaddone', function (e, data) {
        jQuery.each(data.result.files, function (index, file) {
            if (file.url) {
                var link = jQuery('<a>')
                    .attr('target', '_blank')
                    .prop('href', file.url);
                jQuery(data.context.children()[index])
                    .wrap(link);
            } else if (file.error) {
                var error = jQuery('<span class="text-danger"/>').text(file.error);
                jQuery(data.context.children()[index])
                    .append('<br>')
                    .append(error);
            }
        });
    }).on('fileuploadfail', function (e, data) {
        jQuery.each(data.files, function (index, file) {
            var error = jQuery('<span class="text-danger"/>').text('File upload failed.');
            jQuery(data.context.children()[index])
                .append('<br>')
                .append(error);
        });
    }).prop('disabled', !jQuery.support.fileInput)
        .parent().addClass(jQuery.support.fileInput ? undefined : 'disabled');

});

Here are the changes that I made to the default UploadHandler file (making it WordPress friendly):


// Required WordPress files and hooks
require_once( $_SERVER['DOCUMENT_ROOT'] . "/wp-load.php" );
require_once( $_SERVER['DOCUMENT_ROOT'] . "/wp-admin/includes/media.php" );
require_once( $_SERVER['DOCUMENT_ROOT'] . "/wp-admin/includes/file.php" );
require_once( $_SERVER['DOCUMENT_ROOT'] . "/wp-admin/includes/image.php" );

$upload_dir = wp_upload_dir();

global $current_user;
get_currentuserinfo();
$logged_in_user = $current_user->ID;

// Some default blueimp code

// First few lines of the __construct function
global $upload_dir;
$this->options = array(
    'script_url' => $this->get_full_url(),
    'upload_dir' => $upload_dir['path'] . '/',
    'upload_url' => $upload_dir['url'] . '/',

// Some more default blueimp code

// Last line of the get_full_url
substr($_SERVER['DOCUMENT_ROOT'],0, strrpos($_SERVER['DOCUMENT_ROOT'], '/'));

// A lot more default script code

// The handle_file_upload function with WordPress customizations
protected function handle_file_upload($uploaded_file, $name, $size, $type, $error,
    $index = null, $content_range = null) {
    global $logged_in_user;
    $file = new stdClass();
    $file->name = $this->get_file_name($uploaded_file, $name, $size, $type, $error,
    $index, $content_range);
    $file->size = $this->fix_integer_overflow(intval($size));
    $file->type = $type;
    if ($this->validate($uploaded_file, $file, $error, $index)) {
        $this->handle_form_data($file, $index);
        $upload_dir = $this->get_upload_path();
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, $this->options['mkdir_mode'], true);
        }
        $file_path = $this->get_upload_path($file->name);
        $append_file = $content_range && is_file($file_path) &&
            $file->size > $this->get_file_size($file_path);

        if ($uploaded_file && is_uploaded_file($uploaded_file)) {
            // multipart/formdata uploads (POST method uploads)
            if ($append_file) {
                file_put_contents(
                    $file_path,
                    fopen($uploaded_file, 'r'),
                    FILE_APPEND
                );
            } else {
                move_uploaded_file($uploaded_file, $file_path);
            }
        } else {
            // Non-multipart uploads (PUT method support)
            file_put_contents(
                $file_path,
                fopen('php://input', 'r'),
                $append_file ? FILE_APPEND : 0
            );
        }
        $file_size = $this->get_file_size($file_path, $append_file);
        if ($file_size === $file->size) {
            $file->url = $this->get_download_url($file->name);
            if ($this->is_valid_image_file($file_path)) {
                $this->handle_image_file($file_path, $file);
            }
        } else {
            $file->size = $file_size;
            if (!$content_range && $this->options['discard_aborted_uploads']) {
                unlink($file_path);
                $file->error = $this->get_error_message('abort');
            }
        }
        $this->set_additional_file_properties($file);
    }

    $attachment = array(
        'post_mime_type'    => $file->type,
        'post_title'        => preg_replace( '/\\.[^.]+$/', '', basename( $file_path )),
        'post_content'      => '',
        'post_author'       => $logged_in_user,
        'post_status'       => 'inherit',
        'post_type'         => 'attachment',
        'guid'              => $this->options['upload_url'] . $name
    );

    $attachment_id = wp_insert_attachment( $attachment, $file_path );

    // Generate the attachment data
    $attachment_data = wp_generate_attachment_metadata( $attachment_id, $file_path );

    // Update the attachment metadata
    wp_update_attachment_metadata( $attachment_id, $attachment_data );

    return $file;
}