So, I have the following form for image upload:
HTML:
<form name="upload_image">
<input id="fileupload" type="file" name="files[]" class="files rhiu" onchange="UploadImage(event);" accept='image/*'/>
<div id="progress">
<div class="bar" style="width: 0%;"></div>
</div>
<ul id="fileList">
<!-- The file list will be shown here -->
</ul>
</form>
PHP:
add_action( 'wp_ajax_UploadImage', 'UploadImage' );
add_action( 'wp_ajax_nopriv_UploadImage', 'UploadImage' );
function UploadImage()
{
$upload_dir = wp_upload_dir();
$files = $_FILES['files'];
foreach ($files['name'] as $key => $value) {
...ADDING IMAGE TO A POST...
}
}
echo json_encode($image_path);
exit;
}
JS:
function UploadImage(e)
{
var form = document.forms.namedItem("upload_image");
var formdata = new FormData(form);
formdata.append('action', 'UploadImage');
jQuery.ajax({
type: "POST",
dataType: "json",
url: upload_image.ajax_url,
data: formdata,
contentType: false,
processData: false,
success: function(data) {
alert('Success');
}
});
}
As of these, everything works fine.
But I am trying to implement Bluimp jQuery File upload as the uploading handler following the chosen answer here.
I am having a hard time to use the ajax option.
So here is what I am trying to do:
- using the blueimp jQuery file upload to upload images.
- The data are added via ajax function ("UploadImage").
What change do I need to make in the js to include the plugin?
What I tried:
var form = document.forms.namedItem("upload_video");
var formdata = new FormData(form);
formdata.append('action', 'UploadImage');
$('#fileupload').fileupload({
type: "POST",
dataType: "json",
url: upload_image.ajax_url,
data: formdata,
add: function (e, data) {
var tpl = $('<li class="working">'+
'<input type="text" value="0" data-width="48" data-height="48" data-fgColor="#0788a5" data-readOnly="1" data-bgColor="#3e4043" />'+
'<p></p><span></span></li>' );
tpl.find('p')
.text(data.files[0].name)
.append('<i>' + formatFileSize(data.files[0].size) + '</i>');
data.context = tpl.appendTo(ul);
tpl.find('span')
.click(function() {
if (tpl.hasClass('working')) {
jqXHR.abort();
}
tpl.fadeOut(function(){
tpl.remove();
});
});
var jqXHR = data.submit();
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .bar').css(
'width',
progress + '%'
);
}
});