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

Angular中使用PrimeNG p-fileUpload读取JSON并解析为TS对象

解决PrimeNG <p-fileUpload>事件不触发及JSON文件解析问题

一、修复onUpload事件不触发的问题

你的onUpload事件未触发,核心原因是:当设置[auto]="true"时,PrimeNG会自动尝试将文件提交到url指定的后端接口,但你将url设为空字符串,导致提交逻辑失败,而onUpload仅在提交成功后触发,因此不会执行。

如果仅需前端本地读取文件无需提交到后端,建议改用(onSelect)事件(文件选择完成后立即触发),同时可移除无效的url属性:

修改后的HTML代码:

<p-fileUpload #ratingsUpload mode="basic" name="demo[]"
              accept=".json"
              styleClass="p-button-raised"
              [auto]="true" chooseLabel="Upload ratings"
              (onSelect)="onRatingsSelect($event)">
</p-fileUpload>

二、解析JSON文件为TypeScript对象

在TypeScript中,通过FileReader读取文件内容,再将其解析为对应类型的对象:

// 根据你的JSON结构定义对应类型(示例结构,需自行调整)
interface RatingData {
  id: number;
  score: number;
  comment?: string;
}

onRatingsSelect(event: any) {
  const file = event.files[0]; // 获取选中的第一个文件
  if (!file) return;

  // 校验文件类型(增强安全性)
  if (file.type !== 'application/json') {
    console.error('请上传有效的JSON文件');
    return;
  }

  const reader = new FileReader();
  reader.onload = (e) => {
    try {
      // 将文件内容解析为TypeScript对象
      const jsonData: RatingData[] = JSON.parse(e.target?.result as string);
      console.log('解析后的数据:', jsonData);
      // 此处可使用jsonData修改你的数据表
    } catch (error) {
      console.error('JSON解析失败:', error);
    }
  };
  reader.readAsText(file); // 以文本形式读取文件内容
}

额外说明

  • 若确实需要提交文件到后端,需确保url填写正确的接口地址,此时onUpload会在接口返回成功响应后触发,可在回调中处理后端返回数据。
  • 即使设置了accept=".json",仍建议在代码中添加文件类型校验,避免用户上传不符合要求的文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 21:40:39