+ java.net.URLEncoder.encode(fileName, Charset.UTF_8)); if (EmptyUtil.isEmpty(contentType, true)) contentType =
"application/octet-stream"
;
response.setContentType(contentType); os = response.getOutputStream(); byte[] b = new byte[1024]; int size = is.read(b); while (size > 0) os.write(b, 0, size); size = is.read(b);
// MOVE FILE INTO THE WP UPLOADS DIRECTORY AND THEN "UPLOAD" INTO
// AS AN ATTACHMENT IN THE MEDIA GALLERY< AND ASSOCIATED IT TO A SPECIFIC POST
//Start image url
$startImgUrl = __DIR__ . $file['tmp_name'];
//Just the file name (with extension)
$filename = basename($startImgUrl);
//To Uploads directory Path/Url
$wordpress_upload_dir = wp_upload_dir()['path'];
//fetch the image to put into Media Gallery
$contents = file_get_contents($startImgUrl);
// Testing success
if(file_put_contents($wordpress_upload_dir . "/" . $filename, $contents)) {
// UPLOAD ATTACHMENT
// $filename should be the path to a file in the upload directory.
$filename = $wordpress_upload_dir . "/" . $filename;
// Check the type of file. We'll use this as the 'post_mime_type'.
$filetype = wp_check_filetype( basename( $filename ), null );
$ext = $filetype['ext'];
$mime = $filetype['type'];
// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();
// Prepare an array of post data for the attachment.
$attachment = array(
'guid' => $newFile, //full path
'post_mime_type' => $mime,
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit'
);
// Insert the attachment.
$attach_id = wp_insert_attachment( $attachment, $filename);
// SET FEATURED IMAGE OF POST
if(isset($attach_id) && ($attach_id > 0)):
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
if ( ! function_exists( 'wp_generate_attachment_metadata' ) ) {
require_once( ABSPATH . 'wp-admin/includes/image.php' );
}
// The ID of the post this attachment is for. ()
$post_id = $_POST["post_id"];
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $post_id, $attach_id );
endif;
} else {
//echo "file wasn't moved";
}