我正在构建一个插件,我需要上传图像并将其保存到默认wp media文件夹中的单独文件夹和自定义数据库表中。
我设法做到了这两件事,但对于每一张上传的图片,我都会得到一个404 error on the console 我觉得我的方式不好。
代码如下:
<?php ?>
<script>
(function ( $ ) {
$(document).ready(function () {
var i = <?php echo $chapter->id; ?>;
var path = \'<?php echo MT_DIR_PATH . sanitize_title(get_the_title()) . \'_\' . $post->ID . \'/ch_\' . $chapter->chapter_number; ?>\';
var plugin_dir = \'<?php echo MT_URL ?>\';
var manga_id = $(\'#the-post-id\').val();
function upload(i){
var uploader = new plupload.Uploader({
runtimes : \'html5,html4\',
browse_button : \'add-images-\'+i, // you can pass in id...
container: document.getElementById(\'container\'), // ... or DOM Element itself
url : plugin_dir + \'do.php\',
filters : {
max_file_size : \'10mb\',
mime_types: [
{title : \'Image files\', extensions : \'jpg,gif,png\'}
]
},
multipart_params : {
"chapter_id": i,
"path": path
},
init: {
PostInit: function() {
document.getElementById(\'filelist-\'+i).innerHTML = \'\';
document.getElementById(\'start-upload-\'+i).onclick = function() {
uploader.start();
return false;
};
},
FilesAdded: function(up, files) {
plupload.each(files, function(file) {
document.getElementById(\'filelist-\'+i).innerHTML += \'<div id="\' + file.id + \'">\' + file.name + \' (\' + plupload.formatSize(file.size) + \') <b></b></div>\';
});
},
UploadProgress: function(up, file) {
document.getElementById(file.id).getElementsByTagName(\'b\')[0].innerHTML = \'<span>\' + file.percent + "%</span>";
}
}
});
uploader.init();
}
upload(i);
do。php文件
<?php
$filename = $_FILES["file"]["name"];
$special_chars = array("?", "[", "]", "/", "\\\\", "=", "<", ">", ":", ";", ",", "\'", "\\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}");
$filename = str_replace($special_chars, \'\', $filename);
$filename = preg_replace(\'/[\\s-]+/\', \'-\', $filename);
$filename = trim($filename, \'.-_\');
$target_dir = $_POST[\'path\'];
require_once("includes/PluploadHandler.php");
require( \'../../../wp-blog-header.php\' );
PluploadHandler::no_cache_headers();
PluploadHandler::cors_headers();
if (!PluploadHandler::handle(array(
\'target_dir\' => $target_dir,
\'allow_extensions\' => \'jpg,jpeg,png\'
))) {
die(json_encode(array(
\'OK\' => 0,
\'error\' => array(
\'code\' => PluploadHandler::get_error_code(),
\'message\' => PluploadHandler::get_error_message()
)
)));
}
global $wpdb;
$wpdb->insert( $wpdb->prefix . \'mt_images\', array(\'image_name\' => $filename, \'chapter_id\' => $_POST[\'chapter_id\']));
die(json_encode(array(\'OK\' => 1)));
为什么即使图像上载并保存在db中,我也会出现此错误?
我的方法错了吗?