在 GraphQL mutation 中上传文件,如何复用 WordPress 媒体处理逻辑?
解读
面试官真正想考察的是:你是否理解 WordPress 原生文件上传的安全链路、Hook 机制以及如何在 GraphQL 这一“外来”协议里无缝接入这套链路,而不是自己写一套“野路子”上传代码。国内很多团队用 WP 做小程序、App 后端,GraphQL 由 wp-graphql 插件提供,文件上传常成为性能与安全卡点。答出“把文件塞进 wp_handle_upload 然后 insert attachment”只能拿 60 分;答出“复用 plupload 的权限校验、mime 白名单、filter 链、生成多尺寸、触发 cron 压缩、回写 REST 元数据”才能拿满分。
知识点
- wp-graphql 上传协议:客户端 multipart/form-data 带 0 到 N 个 File 变量,GraphQL 端注册
upload类型,解析 PSR-7 Stream。 - WordPress 核心链路:
wp_handle_upload → wp_check_filetype_and_ext → apply_filters(‘wp_handle_upload_prefilter’) → apply_filters(‘wp_handle_upload’) → wp_insert_attachment → wp_generate_attachment_metadata → update_post_meta。 - 权限模型:
upload_files能力 +current_user_can;额外用map_meta_cap过滤自定义角色。 - Hook 注入点:
wp_handle_upload_prefilter:可拦截尺寸、文件名、恶意内容;wp_handle_upload:可切换目录、加 CDN 前缀;add_attachment:可异步推 OSS/ COS;graphql_mutation_input:可二次校验业务字段与文件映射关系。
- 性能与安全:Nginx 先挡 1 MB 以上请求;PHP 侧用
wp_max_upload_size();利用finfo_file二次校验 mime;生成缩略图时复用 WP_Image_Editor_Imagick,避免 OOM。 - 事务一致性:GraphQL mutation 里用
graphql_transaction_isolation_level过滤器把附件写入包进$wpdb->query(‘START TRANSACTION’),失败时wp_delete_file回滚。 - 测试与 CI:在 GitHub Actions 里 mock
$_FILES数组,跑WP_UnitTestCase_Uploads,断言attachment_url_to_postid返回正确 ID。
答案
- 在主题或插件里注册 GraphQL mutation:
add_action( 'graphql_register_types', function() { register_graphql_mutation( 'uploadMediaItem', [ 'inputFields' => [ 'file' => [ 'type' => 'Upload' ], 'title' => [ 'type' => 'String' ], ], 'outputFields' => [ 'mediaItem' => [ 'type' => 'MediaItem' ], ], 'mutateAndGetPayload' => function( $input, $context, $info ) { // 1. 复用 WP 权限 if ( ! current_user_can( 'upload_files' ) ) { throw new \GraphQL\Error\UserError( '无权上传' ); } // 2. 把 GraphQL 解析出的 PSR-7 Stream 转存到临时目录 /** @var \GraphQL\Upload\UploadType $file */ $file = $input['file']; $tmp = $file->getStream()->getMetadata( 'uri' ); // 3. 构造 $_FILES 仿真数组,让 WP 以为这是传统表单上传 $overrides = [ 'test_form' => false, 'mimes' => get_allowed_mime_types(), // 复用后台白名单 ]; $movefile = wp_handle_upload( [ 'name' => $file->getClientFilename(), 'type' => $file->getClientMediaType(), 'tmp_name' => $tmp, 'error' => 0, 'size' => $file->getSize(), ], $overrides ); if ( isset( $movefile['error'] ) ) { throw new \GraphQL\Error\UserError( $movefile['error'] ); } // 4. 插入附件,触发 WP 全部钩子 $attachment_id = wp_insert_attachment( [ 'post_title' => $input['title'] ?: $file->getClientFilename(), 'post_content' => '', 'post_status' => 'inherit', 'post_mime_type' => $movefile['type'], 'guid' => $movefile['url'], ], $movefile['file'] ); // 5. 生成元数据与多尺寸 require_once ABSPATH . 'wp-admin/includes/image.php'; wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $movefile['file'] ) ); // 6. 返回 GraphQL 节点 return [ 'mediaItem' => get_post( $attachment_id ) ]; }, ] ); } ); - 前端调用示例(微信小程序):
mutation($file: Upload!) { uploadMediaItem(input:{file:$file, title:"海报"}) { mediaItem { id sourceUrl mediaDetails { sizes { name sourceUrl } } } } } - 若需接入阿里云 OSS,在
wp_handle_upload过滤器里把文件流推送到 OSS,返回的$movefile['url']改成 CDN 域名即可,无需改动 GraphQL 层。 - 若要做多图一次性上传,可注册
uploadMediaItems批量 mutation,内部循环调用上面同一套函数,保证事务与钩子全部复用。
拓展思考
- 国内 CDN 回源失败重试:在
add_attachment钩子中把文件推送到腾讯 COS,失败时写入自定义表,WP-Cron 每 5 分钟重试;面试可提“用wp_schedule_single_event实现兜底”。 - 大文件分片:Nginx 先配置
client_max_body_size 200M,PHP-FPM 配upload_max_filesize = 200M,但面试追问“200M 以上怎么办”时,可答“用 tus-php 实现断点续传,最终合并后依然走wp_handle_upload,把合并后路径交给 WP 处理,保证缩略图、权限、钩子一条链”。 - 安全加固:在
wp_handle_upload_prefilter里用exif_imagetype二次校验,防止伪造 mime;再对图片进行imagick::stripImage()去除 EXIF 防止 GPS 泄露。 - 测试覆盖:在 CI 里用
wp-cli eval-file跑批量上传,断言数据库post_type=attachment数量与对象存储桶文件数量一致,让面试官看到你懂国内 DevOps 落地场景。