You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress REST API媒体上传报错:无法将文件移至uploads目录

WordPress REST API 图片上传失败:无法移动文件到指定目录的排查方案

可能的问题与解决方法

1. upload_dir 过滤器未正确获取REST API参数

你的自定义目录过滤器使用$_REQUEST获取参数,但在WP REST API请求中,$_REQUEST可能无法正确捕获URL中的查询参数(尤其是POST请求场景)。修改过滤器,改用REST API的请求对象获取参数:

add_filter('upload_dir', 'custom_upload_dir');
function custom_upload_dir($directory) {
    // 仅针对REST API请求处理
    if (defined('REST_REQUEST') && REST_REQUEST) {
        $current_request = wp_get_current_request();
        $query_params = $current_request->get_query_params();
        
        if (isset($query_params['custom_dir']) && !empty($query_params['custom_dir'])) {
            $custom_dir = '/' . sanitize_file_name($query_params['custom_dir']);
            $directory['path'] = str_replace($directory['subdir'], $custom_dir, $directory['path']);
            $directory['url'] = str_replace($directory['subdir'], $custom_dir, $directory['url']);
            $directory['subdir'] = $custom_dir;
        }
    }
    return $directory;
}

2. Python请求的文件上传格式错误

你当前使用data参数直接传递图片二进制数据,不符合WP REST API媒体上传的标准格式(需要multipart/form-data)。修改Python代码,使用files参数上传:

media_endpoint = 'https://wpurl/wp-json/wp/v2/media?custom_dir=news'

# 用files参数构造正确的文件上传请求
files = {
    'file': (image_name, image_data, 'image/jpeg')
}

response = requests.post(
    media_endpoint,
    files=files,
    auth=auth
)

3. 临时文件目录权限问题

WordPress上传文件时会先将文件写入临时目录,再移动到uploads目录。如果临时目录权限不足,也会触发移动失败:

  • 在wp-config.php中显式定义临时目录:
    define('WP_TEMP_DIR', ABSPATH . 'wp-content/temp/');
    
  • 创建wp-content/temp目录,设置权限为755,并确保目录属主与uploads目录一致(比如ploi:www-data)。

4. SELinux 限制(Linux服务器)

如果服务器启用了SELinux,即使文件权限正确,也会阻止PHP操作文件:

  • 临时关闭SELinux测试:
    sudo setenforce 0
    
  • 若测试成功,设置SELinux上下文以允许访问:
    sudo chcon -R -t httpd_sys_rw_content_path /path/to/your/wp-content/uploads
    

5. PHP open_basedir 限制

检查服务器的PHP配置,若open_basedir设置了目录白名单,需确保uploads目录和临时目录在允许范围内:

  • 查看php.ini或站点.htaccess中的open_basedir配置,添加对应目录路径。

内容的提问来源于stack exchange,提问作者Magnus Ohle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 12:35:26