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

使用$.ajax调用WordPress Media接口报错:不允许上传该文件类型

问题分析与修复方案

你的代码存在几个关键问题,导致上传失败:

核心错误点

  • 错误的请求头设置:当使用source_url参数让WordPress抓取远程图片时,不需要设置Content-Type: image/jpeg和Content-Disposition头——这两个头是用于直接上传文件流的场景,反而会干扰REST API对参数的解析。
  • 错误的processData和contentType配置:这两个参数设为false是上传本地文件(用FormData)时的配置,但你是传递source_url参数,需要jQuery自动处理数据编码,所以应该去掉这两个配置或恢复默认值。
  • 数据格式未被正确解析:因为processData: false,jQuery没有把你的featuredImage对象转换为表单编码格式,WordPress无法识别source_url参数,进而触发了错误的文件类型判断。

修正后的代码(远程图片抓取场景)

如果你的.post-thumb输入框里是远程图片的URL,用以下代码:

var featuredImage = {
  source_url: $(".post-thumb").val(),
};

// Ajax调用上传媒体
$.ajax({
  beforeSend: function (xhr) {
    xhr.setRequestHeader("X-WP-Nonce", sovObj.restNonce);
  },
  url: sovObj.restURL + "wp/v2/media",
  type: "POST",
  data: featuredImage,
  success: function (response) {
    console.log(response);
    // 上传成功后,可用response.id作为特色图片ID关联到CPT文章
  },
  error: function (response) {
    console.log(response);
  },
});

如果你要上传本地文件(而非远程URL)

如果你的.post-thumb是文件输入框(<input type="file">),需要用FormData处理文件上传,代码如下:

var fileInput = $(".post-thumb")[0];
if (fileInput.files.length === 0) {
  console.log("请选择图片文件");
  return;
}

var formData = new FormData();
formData.append("file", fileInput.files[0]);

$.ajax({
  beforeSend: function (xhr) {
    xhr.setRequestHeader("X-WP-Nonce", sovObj.restNonce);
  },
  processData: false,
  contentType: false,
  url: sovObj.restURL + "wp/v2/media",
  type: "POST",
  data: formData,
  success: function (response) {
    console.log(response);
  },
  error: function (response) {
    console.log(response);
  },
});

额外检查项

  1. 确保WordPress允许远程图片抓取:可在wp-config.php中临时添加define('ALLOW_UNFILTERED_UPLOADS', true);(生产环境建议通过正规配置或插件管理文件类型)。
  2. 确认source_url指向的是合法的JPEG图片URL,且服务器能正常访问该地址(无跨域或权限限制)。
  3. 验证REST API权限:当前用户需拥有upload_files权限,同时确保nonce值有效。

内容的提问来源于stack exchange,提问作者Akramul Hasan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 21:15:36