I'm using the wp_handle_upload()
function to create a plugin that will give to the users the ability to upload files from front-end using ajax. I've solved an issue relative to an error in the syntax, now while I'm debugging the code I get this error from the function: specified file failed upload test
. I don't know what's wrong with the code, can anyone help me?
PHP
public function upload_form( $attr, $content = null )
{
ob_start();
?>
<form method="POST" enctype="multipart/form-data">
<div class="custom-file">
<input type="file" name="imageFile" class="custom-file-input" id="imageFile" accept="image/*">
<label class="custom-file-label" for="imageFile">Choose file</label>
</div>
<textarea class="form-control" id="imageMessage" name="message"></textarea>
<button type="button" class="btn btn-outline-secondary" id="process-upload"><?php _e('Salva'); ?></button>
<button type="reset" class="btn btn-outline-danger" id="cancel-upload"><?php _e('Annulla'); ?></button>
</form>
<?php
return ob_get_clean();
}
public function process_upload()
{
// $file = array(
// 'name' => $_FILES['imageFile']['name'],
// 'type' => $_FILES['imagefile']['type'],
// 'tmp_name' => $_FILES['imageFile']['tmp_name'],
// 'size' => $_FILES['imageFile']['size'],
// 'error' => $_FILES['imageFile']['error'],
// );
$upload = wp_handle_upload( $_FILES['imagefile'] , array( 'test_form' => false ) );
var_dump($upload);
}
in my js script I have this code:
NB: on the form I've specified the enctype
and the POST method
$('#process-upload').on('click', function(e){
e.preventDefault();
var data = new FormData();
data.append('action', 'new_message');
data.append('imageFile', $('#imageFile').prop('files')[0] );
data.append('message', $('#imageMessage').val() );
$.ajax({
url: wpu.ajaxurl,
type: 'POST',
contentType: false,
processData: false,
data: data,
success: function(response){
console.log(response);
window.alert('Done!');
}
});
});
HTML form
<form method="POST" enctype="multipart/form-data">
<div class="custom-file">
<input type="file" name="imageFile" class="custom-file-input" id="imageFile" accept="image/*">
<label class="custom-file-label" for="imageFile">Choose file</label>
</div>
<textarea class="form-control" id="imageMessage" name="message"></textarea>
<button type="button" class="btn btn-outline-secondary" id="process-upload"><?php _e('Save'); ?></button>
<button type="reset" class="btn btn-outline-danger" id="cancel-upload"><?php _e('Cancel'); ?></button>
</form>