All, I'm using a HTML5 uploader to upload some images. This is part of the file that sends the data to my PHP processing script:
var ajax = $.ajax({
url: ajaxurl,
//dataType: options.ajaxDataType || 'json',
type: options.ajaxType || 'POST',
cache: false,
data: { name: $file.data('filename'), filename: $file.data('file'), file: evt.target.result, data: options.data, action: 'test_upload' },
headers: options.ajaxHeaders,
From the uploader they process the file upload with this code:
if (!empty($_POST)) {
$error = false;
$absolutedir = dirname(__FILE__);
$dir = '/tmp/';
$serverdir = $absolutedir.$dir;
$tmp = explode(',',$_POST['file']);
$file = base64_decode($tmp[1]);
$extension = strtolower(end(explode('.',$_POST['filename'])));
$filename = $_POST['name'].'.'.$extension;
//$filename = $file.'.'.substr(sha1(time()),0,6).'.'.$extension;
$handle = fopen($serverdir.$filename,'w');
fwrite($handle, $file);
fclose($handle);
$response = array(
"result" => true,
"url" => $dir.$filename.'?'.time(), //added the time to force update when editting multiple times
"filename" => $filename
);
echo json_encode($response);
//echo json_encode(array('result'=>true));
}
However, I would like Wordpress to handle my file upload so I'm trying to use the following function to handle my file upload:
function test_upload()
{
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$filename = $_POST['filename'];
$attachment_id = media_handle_upload( $filename, '1' );
print_r($attachment_id);
}
I'm trying to pass the filename because the media_handle_upload codex for the first argument (in my example $filename
) says this:
Index into the $_FILES array of the upload
How can I successfully use WP to upload this file using AJAX to pass me a POST variable instead of a $_FILES variable?
EDIT: When I currently do it this way I get a WP_ERROR saying the file is empty. I created a pastebin with the JS code to handle the file processing form so you can see where the file names are coming from. http://pastebin.com/Shc4KqX1
Here is the file input:
<input type="file" name="file" />