尝试在随机生成的文件夹中以不同于通常的路径上载多个文件uploads/year/month
通过使用wp_upload_bits
.
这是我的代码:
$randomFolder = \'\';
function file_upload_callback() {
global $wpdb;
$table_name = \'wp_order_quotes_real\';
$_filter = true;
add_filter( \'upload_dir\', function( $arr ) use( &$_filter){
if ( $_filter ) {
if ($randomFolder == \'\') {
$randomFolder = substr(str_shuffle("0123456789abcdefghijklmnopqrstvwxyz"), 0, 16);
}
$arr[\'path\'] = $arr[\'basedir\'].\'/order-quotes/\'.$randomFolder;
return $arr;
}
});
_filter = false;
for($i=0; $i < $countfiles; $i++) {
$upload = wp_upload_bits($_FILES[\'file\'][\'name\'][$i], null, file_get_contents($_FILES[\'file\'][\'tmp_name\'][$i]));
}
$dataSubmission = $wpdb->insert(
$table_name, array(
\'order_id\' => $order_id,
\'user_id\' => $user_id ?? \'NULL\',
\'category\' => $cart
),
array(
\'%d\', \'%d\'
)
);
wp_die();
}
add_action( \'wp_ajax_file_upload\', \'file_upload_callback\' );
如果我上载3个文件,它会创建三个随机名称的文件夹,并在每个文件夹中上载单个文件。我想在中上载单个生成文件夹中的所有文件
/order-quotes/
文件夹
最合适的回答,由SO网友:Sally CJ 整理而成
应用以下修复程序(具有// Fix <number>:
注释)并且您的代码将只在一个随机文件夹中工作,该文件夹将为当前会话中的所有上载创建:(注意:我假定$countfiles
在实际代码中正确定义。)
function file_upload_callback() {
global $wpdb;
$table_name = \'wp_order_quotes_real\';
$_filter = true;
$randomFolder = \'\'; // Fix 1: Define the variable.
// Fix 2: Pass $randomFolder by reference to the closure below. That way, the
// value won\'t be changed when the hook calls the closure the next time.
add_filter( \'upload_dir\', function( $arr ) use ( &$_filter, &$randomFolder ) {
if ( $_filter ) {
if ($randomFolder == \'\') {
$randomFolder = ... your code;
}
$arr[\'path\'] = $arr[\'basedir\'].\'/order-quotes/\'.$randomFolder;
// Note: I moved the `return` line to below.
}
return $arr; // Fix 3: ALWAYS return it!
});
//$_filter = false; // Fix 4: Don\'t disable it, yet.
for($i=0; $i < $countfiles; $i++) {
// Note: You should do this because the user may not necessariy upload the
// files in sequence, i.e. file input two might be empty and the user only
// selected a file for the first and third inputs..
if ( empty( $_FILES[\'file\'][\'tmp_name\'][ $i ] ) ) {
continue;
}
$upload = wp_upload_bits( ... your code here... );
}
$_filter = false; // Fix 5: Now you should disable the filter because all the
// uploads have completed.
// ... the rest of your code here.
}
此外,您应该执行以下操作,而不是硬编码表名
$table_name = $wpdb->prefix . \'order_quotes_real\';
. 更重要的是,请采取以下安全措施
checking user capabilities 和
intent of the specific request.