Skip to content

Instantly share code, notes, and snippets.

@NadirZenith
Created April 21, 2014 12:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NadirZenith/11141134 to your computer and use it in GitHub Desktop.
Save NadirZenith/11141134 to your computer and use it in GitHub Desktop.
upload images from front end
$mime = array("image/jpg", "image/jpeg", "image/png");
$uploads = wp_upload_dir();
$upload_files_url = array();
foreach ($_FILES['files']['name'] as $key => $value_data) {
$errors_founds = '';
if ($_FILES['files']['error'][$key] != UPLOAD_ERR_OK)
$errors_founds .= 'Error uploading the file!<br />';
if (!in_array(trim($_FILES['files']['type'][$key]), $mime))
$errors_founds .= 'Invalid file type!<br />';
if ($_FILES['files']['size'][$key] == 0)
$errors_founds .= 'Image file it\'s empty!<br />';
if ($_FILES['files']['size'][$key] > 524288)
$errors_founds .= 'Image file to large, maximus size is 500Kb!<br />';
if (!is_uploaded_file($_FILES['files']['tmp_name'][$key]))
$errors_founds .= 'Error uploading the file on the server!<br />';
if ($errors_founds == '') {
//Sanitize the filename (See note below)
$remove_these = array(' ', '`', '"', '\'', '\\', '/');
$newname = str_replace($remove_these, '', $_FILES['files']['name'][$key]);
//Make the filename unique
$newname = time() . '-' . $newname;
//Save the uploaded the file to another location
$upload_path = $uploads['path'] . "/$newname";
move_uploaded_file($_FILES['files']['tmp_name'][$key], $upload_path);
$upload_files_url[$upload_path] = $uploads['url'] . "/$newname";
}
}
if (count($upload_files_url) > 0) {
$attachs = array();
$i = 0;
foreach ($upload_files_url as $filename_path => $upload_file_url) {
$i++;
$wp_filetype = wp_check_filetype(basename($filename_path), null);
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename_path)),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment($attachment, $filename_path);
$attachs[$i]['id'] = $attach_id;
$attachs[$i]['url'] = wp_get_attachment_url($attach_id);
$attachs[$i]['src'] = wp_get_attachment_image_src($attach_id);
$attachs[$i]['sizes'] = get_intermediate_image_sizes();
// you must first include the image.php file
// for the function wp_generate_attachment_metadata() to work
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata($attach_id, $filename_path);
wp_update_attachment_metadata($attach_id, $attach_data);
}
}
die(); // stop executing script
<form id="fileUploadForm" method="POST" action="<?php echo admin_url('admin-ajax.php'); ?>" enctype="multipart/form-data">
file <input id="fileUploadInput" type="file" name="files[]" multiple="" /> <br>
<!--file <input id="fileUploadInput" type="file" name="myfile[]" multiple="" accept="image/*" /> <br>-->
TOKEN -> hidden <input type="text" name="token"/><br>
action<input type="text" name="action" value="nz_debug"/><br>
<!--nz_token<input type="text" name="nz_token" value="tino"/><br>-->
<input id="fileUploadSubmit" type="submit" value="Submit" /> <br>
</form>
<script>
//
jQuery(document).ready(function($) {
$('#upload-image-button').on('click', selectFile);
function selectFile() {
console.log('selectFile');
if (!selectFile.bound) {
$("#fileUploadInput").on('change', sendForm);
selectFile.bound = true;
}
$('#fileUploadInput').clearFields();
$('#fileUploadInput').click();
}
function sendFile() {
/*$('#fileUploadInput').click();*/
$("#fileUploadInput").change(function() {
sendForm();
/*readURL(this);*/
});
$('#fileUploadInput').click();
}
function sendForm() {
console.log('sendForm');
var options = {
target: '#output',
/*beforeSerialize: function($form, options) {
console.log('before serialize');
console.log($form);
console.log(options);
return true;
},
beforeSubmit: function(arr, form, options) {
console.log('before submit');
console.log(arr);
arr.push({key1: 'value1', key2: 'value2', action: 'ajax_action'});
return true;
},
* */
/*success: showResponse*/
};
//submit NOT IN USE
$('#fileUploadForm2').submit(function() {
console.log('submit');
// inside event callbacks 'this' is the DOM element so we first
// wrap it in a jQuery object and then invoke ajaxSubmit
$(this).ajaxSubmit(options);
return false; //return false to prevent browser request
});
$('#fileUploadForm').ajaxForm(options);
$('#fileUploadSubmit').click();
}
function showRequest(formData, jqForm, options) {
// formData is an array; here we use $.param to convert it to a string to display it
// but the form plugin does this for you automatically when it submits the data
var queryString = $.param(formData);
console.log('About to submit: \n\n' + queryString);
// jqForm is a jQuery object encapsulating the form element. To access the
// DOM element for the form do this:
// var formElement = jqForm[0];
// here we could return false to prevent the form from being submitted;
// returning anything other than false will allow the form submit to continue
return true;
}
// post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
// for normal html responses, the first argument to the success callback
// is the XMLHttpRequest object's responseText property
// if the ajaxForm method was passed an Options Object with the dataType
// property set to 'xml' then the first argument to the success callback
// is the XMLHttpRequest object's responseXML property
// if the ajaxForm method was passed an Options Object with the dataType
// property set to 'json' then the first argument to the success callback
// is the json data object returned by the server
alert('status: ' + statusText + '\n\nresponseText: \n' + responseText +
'\n\nThe output div should have already been updated with the responseText.');
}
});
/*------------------------ ------------------------*/
/*------------- NZ DEBUG ------------------------*/
/*------------------------ ------------------------*/
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
jQuery('#imagePreview').attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment