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

Expo中用XMLHttpRequest上传PDF报Event {"isTrusted": false}错误如何解决

Expo PDF上传错误排查修复方案

排查步骤

  • 修正请求地址:代码中使用的相对路径/upload无法在Expo移动端/模拟器环境下识别,需替换为服务器完整绝对路径,如http://服务器IP:端口/upload。若使用http协议,需提前配置安卓明文流量权限、iOS ATS白名单,避免系统拦截请求。
  • 调整MIME类型配置:FormData中文件的type字段不要使用通配符*/*,需明确指定为PDF对应的application/pdf,避免后端MIME校验拦截。
  • 调整事件监听顺序:xhr.upload.onprogress监听需放在xhr.send()执行前绑定,send执行后再绑定监听会导致事件捕获失效,触发异常。
  • 校验本地文件路径:打印fileToUpload.uri确认路径合法性,需为Expo文件选择器返回的带file://前缀的有效路径,同时确认应用已获取对应文件的访问权限。

修复后代码示例

const xhr = new XMLHttpRequest();
// 替换为你的服务器完整上传地址
xhr.open("POST", "http://你的服务器地址/upload");
xhr.onload = (e) => {
  try {
    const response = JSON.parse(xhr.response);
    console.log(response);
  } catch (err) {
    console.log("响应解析失败", xhr.response);
  }
};
xhr.onerror = (error) => {
  console.log("上传错误", error);
};
xhr.ontimeout = (e) => {
  console.log(e, "upload timeout");
};

// 上传进度监听提前到send之前
if (xhr.upload) {
  xhr.upload.onprogress = ({ total, loaded }) => {
    const uploadProgress = loaded / total;
    console.log("上传进度", uploadProgress);
  };
}

const formData = new FormData();
formData.append("fileToUpload", {
  uri: fileToUpload.uri,
  type: "application/pdf", // 明确指定PDF的MIME类型
  name: fileToUpload.name,
});

xhr.send(formData);

替代上传方案

推荐使用Expo官方封装的expo-file-system的uploadAsync方法,兼容性更强,实现更简洁:

import * as FileSystem from 'expo-file-system';

const uploadResult = await FileSystem.uploadAsync(
  "http://你的服务器地址/upload",
  fileToUpload.uri,
  {
    httpMethod: 'POST',
    uploadType: FileSystem.FileSystemUploadType.MULTIPART,
    fieldName: 'fileToUpload',
    mimeType: 'application/pdf',
    parameters: {
      // 可额外添加其他表单参数
    },
    onUploadProgress: ({ totalBytesSent, totalBytesExpectedToSend }) => {
      const progress = totalBytesSent / totalBytesExpectedToSend;
      console.log("上传进度", progress);
    }
  }
);

// 解析响应
const response = JSON.parse(uploadResult.body);
console.log(response);

使用该方案前需先安装expo-file-system依赖。

内容的提问来源于stack exchange,提问作者kartik tyagi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 23:36:01